<?php
session_start();
include('../connection.php');  // Include your database connection

if ($_SESSION["admin"] != true) {
    header("location:login.php");
    exit;
}

 

function sanitizeInput($data) {
    global $conn;
    return mysqli_real_escape_string($conn, htmlspecialchars(trim($data)));
}

function handleFileUpload($fileInput, $currentPath = '') {
    if (isset($fileInput['error']) && $fileInput['error'] == UPLOAD_ERR_OK) {
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
        $maxSize = 2 * 1024 * 1024; // 2MB
        
        if (!in_array($fileInput['type'], $allowedTypes)) {
            return ['success' => false, 'message' => 'Invalid file type. Only JPG, PNG, and GIF are allowed.'];
        }
        
        if ($fileInput['size'] > $maxSize) {
            return ['success' => false, 'message' => 'File size exceeds 2MB limit.'];
        }
        
        // Delete old file if exists
        if (!empty($currentPath) && file_exists($currentPath)) {
            unlink($currentPath);
        }
        
        $extension = pathinfo($fileInput['name'], PATHINFO_EXTENSION);
        $newFilename = uniqid('img_', true) . '.' . $extension;
        $destination = '../uploads/officers_images/' . $newFilename;
         $destination1 = './uploads/officers_images/' . $newFilename;
        if (move_uploaded_file($fileInput['tmp_name'], $destination)) {
            return ['success' => true, 'path' => $destination1];
        } else {
            return ['success' => false, 'message' => 'Failed to move uploaded file.'];
        }
    }
    
    // Return current path if no new file was uploaded
    return ['success' => true, 'path' => $currentPath];
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $response = ['success' => false, 'message' => ''];

    try {
        if (isset($_POST['action'])) {
            switch ($_POST['action']) {
                case 'addCourt':
                    $courtName = sanitizeInput($_POST['courtName']);
                    $courtStatus = sanitizeInput($_POST['courtstatus']);
                    
                    $query = "INSERT INTO district_courts (court_name, court_status) VALUES (?, ?)";
                    $stmt = $conn->prepare($query);
                    $stmt->bind_param("si", $courtName, $courtStatus);
                    
                    if ($stmt->execute()) {
                        $response = ['success' => true, 'message' => 'Court added successfully.'];
                    } else {
                        $response = ['success' => false, 'message' => 'Error adding court: ' . $stmt->error];
                    }
                    $stmt->close();
                    break;

                case 'addOfficer':
                    $officerName = sanitizeInput($_POST['officerName']);
                    $courtId = sanitizeInput($_POST['officerCourtId']);
                    $officerStatus = sanitizeInput($_POST['officerStatus']);
                    $transferIn = sanitizeInput($_POST['transferIn']);
                    $transferOut = !empty($_POST['transferOut']) ? sanitizeInput($_POST['transferOut']) : null;
                    
                    $fileUpload = handleFileUpload($_FILES['officerImage']);
                    if (!$fileUpload['success']) {
                        echo json_encode($fileUpload);
                        exit;
                    }
                    $imagePath = $fileUpload['path'];
                    
                    $query = "INSERT INTO presiding_officers 
                             (officer_name, court_id, officer_status, transfer_in, transfer_out, pic_path) 
                             VALUES (?, ?, ?, ?, ?, ?)";
                    $stmt = $conn->prepare($query);
                    $stmt->bind_param("siisss", $officerName, $courtId, $officerStatus, $transferIn, $transferOut, $imagePath);
                    
                    if ($stmt->execute()) {
                        $response = ['success' => true, 'message' => 'Officer added successfully.'];
                    } else {
                        $response = ['success' => false, 'message' => 'Error adding officer: ' . $stmt->error];
                    }
                    $stmt->close();
                    break;

                case 'updateOfficer':
                    $id = sanitizeInput($_POST['id']);
                    $officerName = sanitizeInput($_POST['officerName']);
                    $courtId = sanitizeInput($_POST['courtId']);
                    $officerStatus = sanitizeInput($_POST['officerStatus']);
                    $transferIn = sanitizeInput($_POST['transferIn']);
                    $transferOut = !empty($_POST['transferOut']) ? sanitizeInput($_POST['transferOut']) : null;
                    
                    // Get current image path first
                    $currentImagePath = '';
                    $query = "SELECT pic_path FROM presiding_officers WHERE ID = ?";
                    $stmt = $conn->prepare($query);
                    $stmt->bind_param("i", $id);
                    $stmt->execute();
                    $stmt->bind_result($currentImagePath);
                    $stmt->fetch();
                    $stmt->close();
                    
                    $fileUpload = handleFileUpload($_FILES['officerImage'], $currentImagePath);
                    if (!$fileUpload['success']) {
                        echo json_encode($fileUpload);
                        exit;
                    }
                    $imagePath = $fileUpload['path'];
                    
                    $query = "UPDATE presiding_officers 
                             SET officer_name = ?, 
                                 court_id = ?, 
                                 officer_status = ?, 
                                 transfer_in = ?, 
                                 transfer_out = ?, 
                                 pic_path = ? 
                             WHERE ID = ?";
                    $stmt = $conn->prepare($query);
                    $stmt->bind_param("siisssi", $officerName, $courtId, $officerStatus, $transferIn, $transferOut, $imagePath, $id);
                    
                    if ($stmt->execute()) {
                        $response = ['success' => true, 'message' => 'Officer updated successfully.'];
                    } else {
                        $response = ['success' => false, 'message' => 'Error updating officer: ' . $stmt->error];
                    }
                    $stmt->close();
                    break;

                case 'deleteOfficer':
                    $id = sanitizeInput($_POST['id']);
                    
                    // First get image path to delete the file
                    $query = "SELECT pic_path FROM presiding_officers WHERE ID = ?";
                    $stmt = $conn->prepare($query);
                    $stmt->bind_param("i", $id);
                    $stmt->execute();
                    $stmt->bind_result($imagePath);
                    $stmt->fetch();
                    $stmt->close();
                    
                    // Delete the officer record
                    $query = "DELETE FROM presiding_officers WHERE ID = ?";
                    $stmt = $conn->prepare($query);
                    $stmt->bind_param("i", $id);
                    
                    if ($stmt->execute()) {
                        // Delete the image file if it exists
                        if (!empty($imagePath) && file_exists($imagePath)) {
                            unlink($imagePath);
                        }
                        $response = ['success' => true, 'message' => 'Officer deleted successfully.'];
                    } else {
                        $response = ['success' => false, 'message' => 'Error deleting officer: ' . $stmt->error];
                    }
                    $stmt->close();
                    break;

                case 'deleteCourt':
                    $id = sanitizeInput($_POST['id']);
                    
                    $query = "DELETE FROM district_courts WHERE ID = ?";
                    $stmt = $conn->prepare($query);
                    $stmt->bind_param("i", $id);
                    
                    if ($stmt->execute()) {
                        $response = ['success' => true, 'message' => 'Court deleted successfully.'];
                    } else {
                        $response = ['success' => false, 'message' => 'Error deleting court: ' . $stmt->error];
                    }
                    $stmt->close();
                    break;

                default:
                    $response = ['success' => false, 'message' => 'Invalid action specified.'];
                    break;
            }
        } else {
            $response = ['success' => false, 'message' => 'No action specified.'];
        }
    } catch (Exception $e) {
        $response = ['success' => false, 'message' => 'An error occurred: ' . $e->getMessage()];
    }
    
    echo json_encode($response);
    exit;
} else if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    if (isset($_GET['action'])) {
        try {
            switch ($_GET['action']) {
                case 'getCourts':
                    $query = "SELECT ID, court_name, court_status FROM district_courts";
                    $result = mysqli_query($conn, $query);
                    $courts = [];
                    while ($row = mysqli_fetch_assoc($result)) {
                        $courts[] = $row;
                    }
                    echo json_encode($courts);
                    break;

                case 'getOfficers':
                    $query = "SELECT po.ID, po.officer_name, po.court_id, dc.court_name, 
                             po.officer_status, po.transfer_in, po.transfer_out, po.pic_path 
                             FROM presiding_officers po
                             LEFT JOIN district_courts dc ON po.court_id = dc.ID";
                    $result = mysqli_query($conn, $query);
                    $officers = [];
                    while ($row = mysqli_fetch_assoc($result)) {
                        $officers[] = $row;
                    }
                    echo json_encode($officers);
                    break;

                default:
                    echo json_encode(['success' => false, 'message' => 'Invalid action specified.']);
                    break;
            }
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'An error occurred: ' . $e->getMessage()]);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'No action specified.']);
    }
}

mysqli_close($conn);
?>