<?php
include('../config/config.php'); // Ensure DB connection is established

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $action = isset($_POST['action']) ? $_POST['action'] : '';
    $id = isset($_POST['id']) ? $_POST['id'] : '';

    switch ($action) {
        case 'add':
            if (empty($_POST['name']) || empty($_POST['license_no'])) {
                echo "Error: Required fields are missing.";
                exit();
            }

            $stmt = $conn->prepare("INSERT INTO drivers (name, age, address, license_no, phone, status) VALUES (?, ?, ?, ?, ?, 'active')");
            $stmt->bind_param("sisss", $_POST['name'], $_POST['age'], $_POST['address'], $_POST['license_no'], $_POST['phone']);
            echo $stmt->execute() ? "Driver added successfully!" : "Error: " . $stmt->error;
            $stmt->close();
            break;

        case 'edit':
            if (empty($_POST['id']) || empty($_POST['name']) || empty($_POST['license_no'])) {
                echo "Error: Required fields are missing.";
                exit();
            }

            $stmt = $conn->prepare("UPDATE drivers SET name=?, age=?, address=?, license_no=?, phone=? WHERE id=?");
            $stmt->bind_param("sisssi", $_POST['name'], $_POST['age'], $_POST['address'], $_POST['license_no'], $_POST['phone'], $id);
            echo $stmt->execute() ? "Driver updated successfully!" : "Error: " . $stmt->error;
            $stmt->close();
            break;

        case 'delete':
            $stmt = $conn->prepare("UPDATE drivers SET status='inactive' WHERE id=?");
            $stmt->bind_param("i", $id);
            echo $stmt->execute() ? "Driver deleted successfully!" : "Error: " . $stmt->error;
            $stmt->close();
            break;
    }
    exit();
}

if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET['id'])) {
    $id = $_GET['id'];
    $stmt = $conn->prepare("SELECT name, age, address, license_no, phone FROM drivers WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    echo json_encode($result->fetch_assoc());
    $stmt->close();
}
?>
