<?php
namespace App\Controllers\Admin;

use Core\Request;
use Core\Response;
use Core\View;
use App\Models\Responder;
use App\Models\Category;
use App\Models\User;

class ResponderController
{
    public function index()
    {
        $sql = "
            SELECT r.*, u.full_name, u.email, c.name as category_name 
            FROM responders r
            JOIN users u ON r.user_id = u.id
            JOIN categories c ON r.category_id = c.id
        ";
        
        View::make('admin/responders_list')
            ->setLayout('admin_layout')
            ->with([
                'title' => 'Responder Units',
                'responders' => Responder::fetchAll($sql)
            ])->render();
    }

    public function create()
    {
        View::make('admin/responder_form')
            ->setLayout('admin_layout')
            ->with([
                'title' => 'Register New Responder Unit',
                'users' => User::whereAll('role', 'victim'), // Show standard users that can be upgraded
                'categories' => Category::all()
            ])->render();
    }

    public function store()
    {
        $data = Request::all();
        
        // 1. Upgrade the User to a 'responder' role
        User::update($data['user_id'], ['role' => 'responder']);

        // 2. Add them to the Responders table with their base coordinates
        Responder::create([
            'user_id' => $data['user_id'],
            'category_id' => $data['category_id'],
            'organization_name' => $data['organization_name'],
            'base_latitude' => $data['base_latitude'],
            'base_longitude' => $data['base_longitude'],
            'is_available' => 1
        ]);

        return Response::json(['status' => 'success', 'message' => 'Responder Unit registered successfully!', 'redirect' => '/admin/responders']);
    }
    
    // (Edit and Update methods would follow similarly)
    public function edit($id) { /* Render Edit View */ }
    public function update($id) { /* Handle DB Update */ }
}