<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type');

require_once __DIR__ . '/../includes/db_config.php';

session_start();
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    echo json_encode(['success' => false, 'error' => 'Unauthorized access']);
    exit;
}

$m = $_SERVER['REQUEST_METHOD'];

try { $db = getDBConnection(); } catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Database connection failed']);
    exit;
}

try {
    switch ($m) {
        case 'GET':
            $st = $db->prepare("SELECT * FROM delivery_staff ORDER BY created_at DESC");
            $st->execute();
            $rows = $st->fetchAll(PDO::FETCH_ASSOC);
            echo json_encode(['success' => true, 'data' => $rows]);
            break;

        case 'POST':
            $in = json_decode(file_get_contents('php://input'), true);
            if (!$in || !isset($in['name']) || !isset($in['phone']) || !isset($in['password'])) { 
                echo json_encode(['success'=>false,'error'=>'Missing required fields (name, phone, password)']); 
                exit; 
            }

            $hashedPassword = password_hash($in['password'], PASSWORD_DEFAULT);

            $st = $db->prepare("INSERT INTO delivery_staff (name, phone, email, password, status, current_location, total_deliveries, average_delivery_time, rating) VALUES (?, ?, ?, ?, 'available', ?, 0, 0, 0.0)");
            $st->execute([$in['name'], $in['phone'], $in['email'] ?? '', $hashedPassword, $in['location'] ?? '']);

            echo json_encode(['success' => true, 'message' => 'Staff member added successfully']);
            break;

        case 'PUT':
            $in = json_decode(file_get_contents('php://input'), true);
            if (!$in || !isset($in['id'])) { echo json_encode(['success'=>false,'error'=>'Missing staff ID']); exit; }

            if (isset($in['action']) && $in['action'] === 'update_password') {
                if (!isset($in['password']) || empty($in['password'])) {
                    echo json_encode(['success'=>false,'error'=>'Password is required']);
                    exit;
                }
                
                $hashedPassword = password_hash($in['password'], PASSWORD_DEFAULT);
                $st = $db->prepare("UPDATE delivery_staff SET password = ? WHERE id = ?");
                $st->execute([$hashedPassword, $in['id']]);
                echo json_encode(['success'=>true,'message'=>'Password updated successfully']);
                break;
            }

            if (!isset($in['status'])) { echo json_encode(['success'=>false,'error'=>'Missing status field']); exit; }

            $ok = ['available','busy','offline'];
            if (!in_array($in['status'], $ok)) { echo json_encode(['success'=>false,'error'=>'Invalid status']); exit; }

            $st = $db->prepare("UPDATE delivery_staff SET status = ? WHERE id = ?");
            $st->execute([$in['status'], $in['id']]);
            echo json_encode(['success'=>true,'message'=>'Staff status updated successfully']);
            break;

        case 'DELETE':
            $in = json_decode(file_get_contents('php://input'), true);
            if (!$in || !isset($in['id'])) { echo json_encode(['success'=>false,'error'=>'Missing staff ID']); exit; }

            $st = $db->prepare("DELETE FROM delivery_staff WHERE id = ?");
            $st->execute([$in['id']]);
            echo json_encode(['success'=>true,'message'=>'Staff member deleted successfully']);
            break;

        default:
            echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    }

} catch (PDOException $e) {
    echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
}
?>
