<?php
header('Content-Type: text/html; charset=UTF-8');
?>

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

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

$id = $_POST['id'] ?? '';
$print = $_POST['print'] ?? '';

// Fetch the comply_order details

$query = "SELECT `id`, `c_id`, `police_id`, `court_order`, `s_id`, `n_id`, `v_name`, `v_bank`, `v_ac_no`, `v_ifsc`, `time_stamp`, `mobile`, `status` FROM `comply_order` WHERE id = $id";
//$query = "SELECT * FROM comply_order WHERE id = $id";
$result = mysqli_query($con, $query);

if (!$result || mysqli_num_rows($result) === 0) {
    die("No record found.");
}

//$data = mysqli_fetch_assoc($result);
$currentDate = "__/" . date("m/Y");
//$currentDate = date("d/m/Y");
// Optionally fetch related data like police, subject, etc./

if ($kycRow = mysqli_fetch_assoc($result)) {
    $c_id = $kycRow['c_id'];
    // ✅ Move these down, fetched from comply_order (not from cyber_police)
    $accountNo = $kycRow['v_ac_no'];
    $ifscCode = $kycRow['v_ifsc'];
    $courtOrder = $kycRow['court_order'];
    $subjectId = $kycRow['s_id'];
    $noticeId = $kycRow['n_id'];
    $policeId = $kycRow['police_id'];
    $bankId = $kycRow['v_bank'];

    // Fetch cyber_police data using c_id
    $cpQuery = "SELECT * FROM cyber_police WHERE id = '$c_id'";
    $cpResult = mysqli_query($con, $cpQuery);

    if ($cpRow = mysqli_fetch_assoc($cpResult)) {
        $type = $cpRow['atf'];
        switch ($type) {
            case '0':
                $typeLabel = "Acknowledgement";
                break;
            case '1':
                $typeLabel = "FIR";
                break;
            case '2':
                $typeLabel = "Ticket";
                break;
            default:
                $typeLabel = "Unknown";
                break;
        }

        $acknowledgement_no = $cpRow['acknowlegement'];
        $complainant_name = $cpRow['complain_name'];
        $policestationId = $cpRow['pid'];
        $mobile = $cpRow['mobile'];
        $incident_date_time = $cpRow['incident_date_time'];
        $total_fraud_amount = $cpRow['total_fraud_amount'];
        $total_lien_amount = $cpRow['total_lien_amount'];
        $atf = $cpRow['atf'];
        $status = $cpRow['status'];
        $time_stamp = $cpRow['time_stamp'];


    } else {
        echo "No cyber_police record found for this comply_order.";
        exit;
    }


}



// if ($kycRow = mysqli_fetch_assoc($result)) {
//         $c_id = $kycRow['c_id'];

//         // Fetch cyber_police data using c_id
//         $cpQuery = "SELECT * FROM cyber_police WHERE id = '$c_id'";
//         $cpResult = mysqli_query($con, $cpQuery);

//         if ($cpRow = mysqli_fetch_assoc($cpResult)) {
//           $type = $cpRow['atf'];

// // Map ATF type to human-readable string
// switch ($type) {
//     case '0':
//         $typeLabel = "Acknowledgement";
//         break;
//     case '1':
//         $typeLabel = "FIR";
//         break;
//     case '2':
//         $typeLabel = "Ticket"; // if you have a third type
//         break;
//     default:
//         $typeLabel = "Unknown";
//         break;
// }

//             $acknowledgement_no = $cpRow['acknowlegement'];
//             $complainant_name = $cpRow['complain_name'];
//             $policestationId = $cpRow['pid'];
//             $mobile = $cpRow['mobile'];
//             $incident_date_time = $cpRow['incident_date_time'];
//             $total_fraud_amount = $cpRow['total_fraud_amount'];
//             $total_lien_amount = $cpRow['total_lien_amount'];
//             $atf = $cpRow['atf'];
//             $status = $cpRow['status'];
//             $time_stamp = $cpRow['time_stamp'];

//             $accountNo = $cpRow['v_ac_no'];
// $ifscCode = $cpRow['v_ifsc'];
// $courtOrder = $cpRow['court_order'];
// $subjectId = $cpRow['s_id'];
// $subjectId = $cpRow['n_id'];
// $policeId = $cpRow['police_id'];
// $bankId = $cpRow['v_bank'];
// $subjectName = "";

//         } else {
//             echo "No cyber_police record found for this KYC.";
//             exit;
//         }
//     } else {
//         echo "KYC record not found.";
//         exit;
//     }




// Police name
if ($kycRow['v_bank']) {
    $res = $con->query("SELECT b_name FROM bank WHERE id = " . (int) $kycRow['v_bank']);
    if ($res && $res->num_rows > 0) {
        $bankName = $res->fetch_assoc()['b_name'];
    }
}


// Police 
$policeInfo = [];
if ($kycRow['police_id']) {
    $res = $con->query("SELECT id, pid, i_name, i_number, i_designation, i_sign FROM police WHERE id = " . (int) $kycRow['police_id']);
    if ($res && $res->num_rows > 0) {
        $policeInfo = $res->fetch_assoc();
    }
}


// Subject name
if ($kycRow['s_id']) {
    $res = $con->query("SELECT s_name FROM subject WHERE id = " . (int) $kycRow['s_id']);
    if ($res && $res->num_rows > 0) {
        $subjectName = $res->fetch_assoc()['s_name'];
    }
}

// Police station
$stationInfo = [];
$res = $con->query("SELECT id, spid, p_name, p_address, p_landline, p_number, p_email, timestamp FROM policestation WHERE id = " . (int) $policestationId);
if ($res && $res->num_rows > 0) {
    $stationInfo = $res->fetch_assoc();
}


// Fetch c_bank_data entries with bank name
$bankData = [];
$bankQuery = "SELECT cb.*, b.b_name 
              FROM c_bank_data cb 
              LEFT JOIN bank b ON cb.bank_id = b.id 
              WHERE cb.comply_order_id = $id";
$bankResult = mysqli_query($con, $bankQuery);

if ($bankResult && mysqli_num_rows($bankResult) > 0) {
    while ($row = mysqli_fetch_assoc($bankResult)) {
        $bankData[] = $row;
    }
}

$policeInfo['i_name'];
$policeInfo['i_number'];
$policeInfo['i_designation'];
$policeInfo['i_sign'];
$stationInfo['p_name'];
$stationInfo['p_address'];
$stationInfo['p_landline'];
$stationInfo['p_number'];
$stationInfo['p_email'];

$policeStationName = $stationInfo['p_name'];
$pAddress = $stationInfo['p_address'];
$pLandLine = $stationInfo['p_landline'];
$pEmail = $stationInfo['p_email'];
$policeName = $policeInfo['i_name'];
$policeDesignation = $policeInfo['i_designation'];
$policeNumber = $policeInfo['i_number'];
$accountNo = $kycRow['v_ac_no'];
$ifscCode = $kycRow['v_ifsc'];
$banknameLatter = "";

$acNo_name_victim = $bankName . "<br>" . $complainant_name . "<br>" . $accountNo;

$releaseInstructions = '';

if ($print === 'true') {
    echo '<script>window.onload = function() { window.print(); }</script>';
}

?>

<?php
// Group bank data by bank name
$groupedBankData = [];
foreach ($bankData as $item) {
    $groupedBankData[$item['b_name']][] = $item;
}

?>

<?php foreach ($groupedBankData as $bankName => $entries): ?>

    <?php
    $releaseInstructions = "This is to bring to your kind notice that $courtOrder, has given direction to $policeStationName stating to give direction to concerned ";

    $sentences = [];
    foreach ($entries as $cpRow) {
        $accno = $cpRow['account_number'];
        $amount = $cpRow['release_amount'];
        $sentences[] = "Manager of $bankName account No.$accno to de-freeze the amount of Rs.$amount/-";
    }

    $releaseInstructions .= implode(" & ", $sentences);

    // Complainant's bank details
    $complainantBankName = '';
    if (!empty($bankId)) {
        $res = $con->query("SELECT b_name FROM bank WHERE id = " . (int) $bankId);
        if ($res && $res->num_rows > 0) {
            $complainantBankName = $res->fetch_assoc()['b_name'];
        }
    }

    $complainantAcc = htmlspecialchars($accountNo);
    $complainantIFSC = htmlspecialchars($ifscCode);

    $releaseInstructions .= " and release the said amount to the account of complainant’s $complainantBankName Account No.$complainantAcc IFSC Code-$complainantIFSC and submit the report to the court forthwith.";
    ?>

    <!DOCTYPE html>
    <html>

    <head>
        <meta charset="UTF-8">
        <title>BANK-COMPLY ORDER</title>
        <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
        <link rel="stylesheet" href="css/styles.css"> <!-- External CSS file -->
    </head>

    <body>

        <div class="a4-container">
            <!-- Header -->
            <div class="header-container">
                <img src="images/gp_logo.png" class="logo-left" alt="Police Logo">
                <div class="header-text">
                    <h2><?php echo $policeStationName ?></h2>
                    <p><?php echo htmlspecialchars($pAddress); ?></p>
                    <p>Tel. no. <?php echo $pLandLine ?></p>
                    <p class="email">E-mail ID: <?php echo $pEmail; ?></p>
                </div>
                <img src="images/azadi.png" class="logo-right" alt="Azadi Ka Amrit Mahotsav">
            </div>

            <!-- Title -->
            <div class="section-title">
                <?php //echo strtoupper($noticeName); ?>
            </div>

            <!-- Outward block right aligned -->
            <div class="outward-details">
                <div class="outward-box">
                    <b>
                        Outward number _________/2025,<br>
                        Date-<?php echo $currentDate; ?>
                    </b>
                </div>
            </div>

            <!-- Recipient Info for each bank -->
            <div class="to-box">
                <b>
                    To,<br>
                    Nodal officer / The Manager<br>
                    <?php echo htmlspecialchars($bankName); ?>
                </b>
            </div>

            <center style="margin-top: 5px;">
                <table>
                    <tr>
                        <td><strong>Subject:</strong> <?php echo $subjectName; ?></td>
                    </tr>
                    <tr>
                        <td><strong>Reference:</strong> (1)
                            <?php
                            $typeLabel = '';
                            if ($type == 0) {
                                $typeLabel = 'Acknowledgement Number ';
                            } elseif ($type == 1) {
                                $typeLabel = 'Ticket Number ';
                            } elseif ($type == 2) {
                                $typeLabel = 'FIR Number';
                            }
                            ?>
                            <b><?php echo $typeLabel; ?> : <strong><?php echo $acknowledgement_no; ?></strong>
                        </td>
                    </tr>
                </table>
            </center>

            <!-- Release Instruction -->
            <div class="letter-body">
                <p>Dear Sir/Madam,</p>
                <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <?php echo $releaseInstructions ?> has given direction to
                    <?php echo $policeStationName; ?> stating to give direction to concerned
                    Manager of <?php echo $bankName; ?> accounts as below:
                </p>
            </div>

            <div class="account-table">
                <table class="w3-table-all w3-bordered">
                    <thead>
                        <tr>
                            <th>Victim Account Number and Name</th>
                            <th>IFSC Code</th>
                            <th>Suspect Account Number and Name</th>
                            <th>IFSC Code</th>
                            <th>Release Amount</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($entries as $entry): ?>
                            <tr>
                                <td><?php echo $acNo_name_victim; ?></td>
                                <td><?php echo htmlspecialchars($ifscCode); ?></td>
                                <td><?php echo htmlspecialchars($entry['b_name']) . "<br>" . htmlspecialchars($entry['account_holder']) . "<br>" . htmlspecialchars($entry['account_number']); ?>
                                </td>
                                <td><?php echo htmlspecialchars($entry['ifsc_code']); ?></td>
                                <td><?php echo htmlspecialchars($entry['release_amount']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <div class="instruction-block">
                <p>
                    Therefore, you are hereby directed to act according to the order passed by the honorable court and
                    comply
                    with this order in writing in <b>3 days</b>. A scanned copy of the court order is attached herewith for
                    your
                    kind
                    perusal.
                </p>
                <p> Thanking you, </p>
            </div>

            <!-- Signature Block -->
            <div class="signature-container">
                <div class="signature-block">
                    <b>
                        (<?php echo strtoupper($policeName); ?>)<br>
                        <?php echo strtoupper($policeDesignation); ?><br>
                        <?php echo strtoupper($policeStationName); ?><br>
                        <?php echo strtoupper($pAddress); ?><br>
                        <?php echo strtoupper($policeNumber); ?>
                    </b>
                </div>
            </div>

        </div>

    </body>

    </html>
<?php endforeach; ?>