<?php
session_start();
include "config.php";

// Redirect if user not logged in
if (!isset($_SESSION['user'])) {
    header("Location: index.php");
    exit();
}

$user = $_SESSION['user'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get and sanitize form inputs

    $atf = $_POST['atf'];
    $police_id = isset($_POST['police_id']) ? intval($_POST['police_id']) : null;
    $subject_id = isset($_POST['subject_id']) ? intval($_POST['subject_id']) : null;
    $notice_id = isset($_POST['notice_id']) ? intval($_POST['notice_id']) : null;

    // Bank accounts JSON from hidden field
    $bank_accounts_json = isset($_POST['bank_accounts_json']) ? $_POST['bank_accounts_json'] : '[]';

    // Validate required fields (simple example)
    if (!$atf || !$police_id || !$subject_id || !$notice_id) {
        die("Please fill in all required fields.");
    }

    // Prepare data for insertion
    $uid = $user['id'];  // Assuming user id is stored as 'id' in session user data
    $pid = $user['pid']; // Police station id associated with user
    $cctv_details = mysqli_real_escape_string($con, $bank_accounts_json);
    $timestamp = date('Y-m-d H:i:s');

    // Insert query
    $insertQuery = "INSERT INTO `cctv` 
        (`c_id`, `police_id`, `n_id`, `s_id`, `cctv_details`, `time_stamp`,`mobile`,`status`,`remarks`) 
        VALUES 
        ('$atf', '$police_id', '$notice_id', '$subject_id','$cctv_details', '$timestamp','no','','')";

    if (mysqli_query($con, $insertQuery)) {
        // Success - redirect or show success message
        header("Location: cctv.php?msg=Data saved successfully");
        exit();
    } else {
        // Error
        echo "Error: " . mysqli_error($con);
    }
} else {
    echo "Invalid request method.";
}
?>