<?php
session_start();
$brcode = $_SESSION['brcode'];
$user = $_SESSION['user'];

if (strlen($brcode) <= 0) {
    echo "<script>alert('Session timed out'); parent.document.location='index.php';</script>";
    exit;
}

include("../opendb.php");

if (isset($_GET['approve']) && isset($_GET['jvno']) && isset($_GET['brcode'])) {
    $jvno = mysqli_real_escape_string($db, $_GET['jvno']);
    $br = mysqli_real_escape_string($db, $_GET['brcode']);
    
    $date = date("d-m-Y H:i:s");

    $update = "UPDATE gen4psnauto_psn_forcedb2526.journal2_approval SET tr_no='$user' approve='Y', approve_date='$date' WHERE jvno='$jvno' AND brcode='$br'";
    
    mysqli_query($db, $update) or die(mysqli_error($db));

    $brres_2 = mysqli_query($db, "SELECT MAX(jvno) FROM gen4psnauto_psn_forcedb2526.journal2 WHERE brcode='$br'");
    $brrow_2 = mysqli_fetch_array($brres_2);
    $jvno_2 = $brrow_2[0] + 1;

    $res = mysqli_query($db, "SELECT * FROM gen4psnauto_psn_forcedb2526.journal2_approval WHERE jvno='$jvno' AND brcode='$br'");
    while ($row = mysqli_fetch_assoc($res)) {
        $columns = [];
        $values = [];
        foreach ($row as $key => $val) {
            if ($key == 'approve' || $key == 'approve_date' || $key == 'id') continue;
            if ($key == 'jvno') {
                $columns[] = 'jvno';
                $values[] = "'$jvno_2'";
            } else {
                $columns[] = $key;
                $values[] = "'" . mysqli_real_escape_string($db, $val) . "'";
            }
        }

        $columns_str = implode(',', $columns);
        $values_str = implode(',', $values);
        // echo "<pre>";
        // echo $columns_str;
        // echo $values_str;
        // echo "</pre>";
        // exit();
        // die();

        $insert = "INSERT INTO gen4psnauto_psn_forcedb2526.journal2 ($columns_str) VALUES ($values_str)";
        mysqli_query($db, $insert) or die(mysqli_error($db));
    }

    echo "<script>alert('Approved and transferred to journal2 successfully'); window.location='approvebrnew_force.php';</script>";
    exit;
}

$sql = "SELECT * FROM gen4psnauto_psn_forcedb2526.journal2_approval WHERE brcode='$brcode' ORDER BY date DESC, jvno";

$res = mysqli_query($db, $sql) or die(mysqli_error($db));

$data = [];
while ($r = mysqli_fetch_assoc($res)) {
    $key = $r['brcode'].'_'.$r['jvno'];
    $data[$key]['rows'][] = $r;
    $data[$key]['approve'] = $r['approve'];
    $data[$key]['approve_date'] = $r['approve_date'];
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Journal Approval</title>
    <style>
        body {
            font-family: 'Segoe UI', sans-serif;
            background: #f0f6f9;
            margin: 0;
            padding: 20px;
        }
        .container {
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        h2 {
            color: #347d90;
            margin-bottom: 20px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 25px;
        }
        th {
            background: #c1d799;
            padding: 10px;
            text-align: left;
        }
        td {
            background: #e3ecd2;
            padding: 8px;
        }
        tr:nth-child(even) td {
            background: #f5f9f0;
        }
        a.approve-btn {
            background: #347d90;
            color: #fff;
            padding: 6px 12px;
            border-radius: 4px;
            text-decoration: none;
            font-size: 14px;
        }
        a.approve-btn:hover {
            background: #285f6d;
        }
        .approved {
            color: green;
            font-weight: bold;
        }
        .group-header {
            background: #c1d799;
            font-weight: bold;
        }
    </style>
</head>
<body>
<div class="container">
    <h2>Journal Entry Approval - Branch: <?php echo htmlspecialchars($brcode); ?></h2>

    <?php
    if (empty($data)) {
        echo "<p>No records found.</p>";
    } else {
        foreach ($data as $key => $group) {
            $first = $group['rows'][0];
            $jvno = $first['jvno'];
            $br = $first['brcode'];
            $status = $group['approve'];
            $date = $group['approve_date'];
            ?>

            <table border="1">
                <tr class="group-header">
                    <td colspan="9">
                        <strong>JV No:</strong> <?php echo $jvno; ?> &nbsp;|&nbsp;
                        <strong>Branch:</strong> <?php echo $br; ?> &nbsp;|&nbsp;
                        <strong>Status:</strong>
                        <?php
                        if ($status == 'Y') {
                            echo "<span class='approved'>Approved ($date)</span>";
                        } else {
                            echo "<span style='color:red;font-weight:bold;'>Pending</span>";
                        }
                        ?>
                        <?php if ($status != 'Y') { ?>
                            &nbsp;&nbsp;
                            <a class="approve-btn" href="?approve=1&jvno=<?php echo $jvno; ?>&brcode=<?php echo $br; ?>"
                               onclick="return confirm('Approve all entries for JV No <?php echo $jvno; ?>?')">Approve</a>
                        <?php } ?>
                    </td>
                </tr>
                <tr>
                    <th>Date</th>
                    <th>Type</th>
                    <th>Particular</th>
                    <th>Dr Amt</th>
                    <th>Cr Amt</th>
                    <th>Narration</th>
                    <th>Against</th>
                    <th>J Type</th>
                    <th>No</th>
                </tr>
                <?php foreach ($group['rows'] as $row) { ?>
                    <tr>
                        <td><?php echo $row['date']; ?></td>
                        <td><?php echo $row['type']; ?></td>
                        <td><?php echo htmlspecialchars($row['partic']); ?></td>
                        <td><?php echo number_format($row['dramt'], 2); ?></td>
                        <td><?php echo number_format($row['cramt'], 2); ?></td>
                        <td><?php echo htmlspecialchars($row['narr']); ?></td>
                        <td><?php echo htmlspecialchars($row['against']); ?></td>
                        <td><?php echo htmlspecialchars($row['j_type']); ?></td>
                        <td><?php echo htmlspecialchars($row['no']); ?></td>
                    </tr>
                <?php } ?>
            </table>
        <?php
        }
    }
    ?>
</div>
</body>
</html>
