<?php
header("Content-Type: application/json");
// Include database configuration
include "../config.php";


// Only handle POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Read and decode the JSON input
    $rawData = file_get_contents("php://input");
    $data = json_decode($rawData, true);

    // Validate JSON decoding
    if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
        http_response_code(400);
        echo json_encode(["error" => "Invalid JSON format."]);
        exit();
    }

    // Extract and sanitize fields
    $atf     = $data['atf'] ?? '';
    $ack_no             = isset($data['ack_no']) ? intval($data['ack_no']) : null;
    $complainant_name   = isset($data['complainant_name']) ? mysqli_real_escape_string($con, $data['complainant_name']) : '';
    $policestation_id   = isset($data['policestation_id']) ? intval($data['policestation_id']) : null;
    $police_id          = isset($data['police_id']) ? intval($data['police_id']) : null;
    $subject_id         = isset($data['subject_id']) ? intval($data['subject_id']) : null;
    $notice_id          = isset($data['notice_id']) ? intval($data['notice_id']) : null;
    $cctv_details       = isset($data['cctv_details']) ? json_encode($data['cctv_details'], JSON_UNESCAPED_UNICODE) : '[]';

    $uid                = $data['uid'] ?? null;
    $pid                = $data['pid'] ?? null; // Police station ID (from user or frontend
    $mobile = 'true';

    $timestamp = date('Y-m-d H:i:s');

    // Basic required field validation
    if (!$uid || !$pid || !$ack_no || !$complainant_name || !$policestation_id || !$police_id || !$subject_id || !$notice_id) {
        http_response_code(400);
        echo json_encode(["error" => "Missing required fields."]);
        exit();
    }

    // Insert into CCTV table
    $query = "INSERT INTO `cctv` 
        (`uid`, `pid`, `police_id`, `notice_id`, `subject_id`, `acknowledgement_no`, `complainant_name`, `cctv_details`, `time_stamp`, `atf`,`mobile`) 
        VALUES 
        ('$uid', '$pid', '$police_id', '$notice_id', '$subject_id', '$ack_no', '$complainant_name', '$cctv_details', '$timestamp', '$atf','$mobile')";

    if (mysqli_query($con, $query)) {
        echo json_encode([
            "success" => true,
            "message" => "CCTV data saved successfully",
            "cctv_id" => mysqli_insert_id($con)
        ]);
    } else {
        http_response_code(500);
        echo json_encode([
            "error" => "Database insertion failed",
            "details" => mysqli_error($con)
        ]);
    }
} else {
    http_response_code(405); // Method Not Allowed
    echo json_encode(["error" => "Only POST requests are allowed."]);
}
?>