<?php
// Include the database connection file
include('../connection.php');

// Constants
define('UPLOAD_DIR', '../uploads/Judgments/');
define('MAX_FILE_SIZE', 2097152); // 2MB

// Utility function to check for duplicate judgments
function checkDuplicateJudgment($conn, $caseNumber, $officerName) {
    $stmt = $conn->prepare("SELECT 1 FROM judgments WHERE CaseNumber = ? AND OfficerName = ?");
    $stmt->bind_param("ss", $caseNumber, $officerName);
    $stmt->execute();
    $stmt->store_result();
    return $stmt->num_rows > 0;
}

// Utility function to handle file uploads
function handleFileUpload($file) {
    if (!is_dir(UPLOAD_DIR)) {
        mkdir(UPLOAD_DIR, 0755, true);
    }

    $fileName = basename($file['name']);
    $filePath = UPLOAD_DIR . $fileName;

    // Validate file type and size
    $allowedTypes = ['application/pdf', 'text/plain'];
    if (!in_array($file['type'], $allowedTypes)) {
        return ['error' => 'Invalid file type. Only PDF and plain text files are allowed.'];
    }

    if ($file['size'] > MAX_FILE_SIZE) {
        return ['error' => 'File size exceeds the 2MB limit.'];
    }

    if (move_uploaded_file($file['tmp_name'], $filePath)) {
        return ['success' => true, 'path' => $filePath];
    } else {
        return ['error' => 'Failed to upload file.'];
    }
}

// Insert or Update a judgment
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['judgmentFile'])) {
    header('Content-Type: application/json');
    $fileUpload = handleFileUpload($_FILES['judgmentFile']);
    if (isset($fileUpload['error'])) {
        echo json_encode(['success' => false, 'message' => $fileUpload['error']]);
        exit;
    }

    $judgmentText = $fileUpload['path'];
    $officerName = $_POST['officerName'];
    $caseNumber = $_POST['caseNumber'];
    $caseType = $_POST['caseType'];
    $judgmentDate = $_POST['judgmentDate'];
    $courtID = $_POST['courtID'];
    $judgmentID = $_POST['judgmentID'] ?? null;

    if (empty($judgmentID)) {
        if (checkDuplicateJudgment($conn, $caseNumber, $officerName)) {
            echo json_encode(['success' => false, 'message' => 'Duplicate judgment found.']);
            exit;
        }

        $stmt = $conn->prepare("INSERT INTO judgments (OfficerName, CaseNumber, CaseType, JudgmentDate, court_id, JudgmentText) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssssis", $officerName, $caseNumber, $caseType, $judgmentDate, $courtID, $judgmentText);
    } else {
        $stmt = $conn->prepare("UPDATE judgments SET OfficerName = ?, CaseNumber = ?, CaseType = ?, JudgmentDate = ?, court_id = ?, JudgmentText = ? WHERE ID = ?");
        $stmt->bind_param("ssssisi", $officerName, $caseNumber, $caseType, $judgmentDate, $courtID, $judgmentText, $judgmentID);
    }

    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'message' => 'Record saved successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error: ' . $stmt->error]);
    }
    exit;
}

// Handle delete request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['deleteID'])) {
    $deleteID = $_POST['deleteID'];

    $stmt = $conn->prepare("DELETE FROM judgments WHERE ID = ?");
    $stmt->bind_param("i", $deleteID);

    if ($stmt->execute()) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error: ' . $stmt->error]);
    }
    exit;
}

// Fetch courts for dropdown
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['fetchCourts']) && $_GET['fetchCourts'] === 'true') {
    $result = $conn->query("SELECT ID, court_name FROM district_courts WHERE court_status = 1");
    $courts = $result->fetch_all(MYSQLI_ASSOC);
    echo json_encode(['success' => true, 'courts' => $courts]);
    exit;
}

// Fetch all judgments
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $searchQuery = isset($_GET['searchQuery']) ? '%' . $_GET['searchQuery'] . '%' : '';
    $stmt = $conn->prepare("SELECT * FROM judgments WHERE CaseNumber LIKE ? OR OfficerName LIKE ?");
    $stmt->bind_param("ss", $searchQuery, $searchQuery);
    $stmt->execute();
    $judgments = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    echo json_encode($judgments);
    exit;
}

$conn->close();
?>
