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

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    if (isset($_GET['action']) && $_GET['action'] == 'fetchCourts') {
        // Fetch court data for the dropdown
        $query = "SELECT `ID`, `court_name` FROM `district_courts` WHERE `court_status` = 1";
        $result = $conn->query($query);

        $courts = [];
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $courts[] = $row;
            }
        }
        header('Content-Type: application/json');
        echo json_encode($courts);
    } else if (isset($_GET['action']) && $_GET['action'] == 'fetchCauselists') {
        // Fetch causelists for the table
        $query = "SELECT c.ID, dc.court_name, c.causelist_date, c.file_link 
                  FROM causelist c 
                  JOIN district_courts dc ON c.court_id = dc.ID";
        $result = $conn->query($query);

        $causelists = [];
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $causelists[] = $row;
            }
        }
        header('Content-Type: application/json');
        echo json_encode($causelists);
    } else if (isset($_GET['action']) && $_GET['action'] == 'delete') {
        $id = intval($_GET['id']);
        $file_query = "SELECT `file_link` FROM `causelist` WHERE `ID` = ?";
        $stmt = $conn->prepare($file_query);
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $file_result = $stmt->get_result();
        $file_path = null;

        if ($file_result->num_rows > 0) {
            $row = $file_result->fetch_assoc();
            $file_path = $row['file_link'];
        }

        $query = "DELETE FROM `causelist` WHERE `ID` = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("i", $id);

        if ($stmt->execute()) {
            if ($file_path && file_exists($file_path)) {
                unlink($file_path);
            }
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'error' => $stmt->error]);
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $court_id = $_POST['court_id'];
    $causelist_date = $_POST['causelist_date'];

    $check_query = "SELECT * FROM `causelist` WHERE `court_id` = ? AND `causelist_date` = ?";
    $stmt = $conn->prepare($check_query);
    $stmt->bind_param("is", $court_id, $causelist_date);
    $stmt->execute();
    $check_result = $stmt->get_result();

    if ($check_result->num_rows > 0) {
        echo json_encode(['success' => false, 'message' => 'Duplicate entry: A similar causelist already exists.']);
        exit;
    }

    $target_dir = "../uploads/Cause List/";
    $file_name = basename($_FILES["file_link"]["name"]);
    $target_file = $target_dir . $file_name;

    $allowed_types = ['application/pdf'];
    if (!in_array($_FILES["file_link"]["type"], $allowed_types)) {
        echo json_encode(['success' => false, 'message' => 'Invalid file type. Only PDF files are allowed.']);
        exit;
    }

    if ($_FILES["file_link"]["size"] > 5 * 1024 * 1024) {
        echo json_encode(['success' => false, 'message' => 'File size exceeds the 5MB limit.']);
        exit;
    }

    if (!is_dir($target_dir)) {
        mkdir($target_dir, 0777, true);
    }

    if (move_uploaded_file($_FILES["file_link"]["tmp_name"], $target_file)) {
        $sql = "INSERT INTO `causelist` (`court_id`, `causelist_date`, `file_link`) VALUES (?, ?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("iss", $court_id, $causelist_date, $target_file);

        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'message' => 'Causelist uploaded successfully.']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Database error: ' . $stmt->error]);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to upload file.']);
    }
}

$conn->close();
?>
