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

if (!isset($_SESSION['user'])) {
    echo '<script>window.location.href = "index.php";</script>';
    exit();
}

$user = $_SESSION['user'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $reference_type = $_POST['reference_type'] ?? '';
    $ackNo = $_POST['ack_no'] ?? '';
    $complainantName = $_POST['complainant_name'] ?? '';
    $mobile = $_POST['mobile'] ?? '';
    $incidentDateTime = $_POST['incident_date_time'] ?? '';
    $totalFraudAmount = $_POST['total_fraud_amount'] ?? '';
    $totalLienAmount = $_POST['total_lien_amount'] ?? '';
    $status = $_POST['status'] ?? 'Pending';
    $pid = $user['pid'];

    // Check if acknowledgment number already exists and get police station info
    $checkQuery = "
        SELECT cp.acknowlegement, cp.complain_name, cp.mobile, ps.p_name, ps.p_number
        FROM cyber_police cp
        JOIN policestation ps ON cp.pid = ps.id
        WHERE cp.acknowlegement = '$ackNo'
        LIMIT 1
    ";

    $result = mysqli_query($con, $checkQuery);

    if (mysqli_num_rows($result) > 0) {
        $existing = mysqli_fetch_assoc($result);
        $existingName = $existing['complain_name'];
        $existingAck = $existing['acknowlegement'];
        $existingMobile = $existing['mobile'];
        $policeName = $existing['p_name'];
        $policeContact = $existing['p_number'];

        echo "<script>
                alert('Record already exists!\\nName: $existingName\\nAck No: $existingAck\\nMobile: $existingMobile\\nThis record belongs to Police Station: $policeName, Contact: $policeContact');
                window.location.href = 'atf.php';
              </script>";
        exit();
    }

    // Insert new record
    $insertQuery = "
        INSERT INTO cyber_police 
        (acknowlegement, complain_name, mobile, incident_date_time, total_fraud_amount, total_lien_amount, atf, pid, status)
        VALUES
        ('$ackNo', '$complainantName', '$mobile', '$incidentDateTime', '$totalFraudAmount', '$totalLienAmount', '$reference_type', '$pid', '$status')
    ";

    if (mysqli_query($con, $insertQuery)) {
        echo '<script>alert("Record inserted successfully!"); window.location.href = "atf.php";</script>';
    } else {
        echo '<script>alert("Error inserting record: ' . mysqli_error($con) . '");</script>';
    }

    exit();
}
?>