<?php
include("db/cn.php");
include('common/tx.php');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
ob_start();

if (isset($_SESSION['user_name']) && isset($_SESSION['user_role']) && isset($_SESSION['outlet_name']) && isset($_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
    $outlet_address = $_SESSION['outlet_address'];
    $outlet_name = $_SESSION['outlet_name'];
} else {
    echo '<script type="text/javascript">window.location.href="logout.php";</script>';
    exit();
}
@$id = $_GET['id'];
// --- Handle Supplier Paid UPDATE (SAME PAGE) ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["supplier_paid"])) {

    $id          = (int) $_POST["paid_id"];
    $date_time   = $_POST["date_time"] ?? date("Y-m-d");
    $supplier    = $_POST["supplier_name"];
    $amount      = $_POST["supplier_amount"];
    $description = $_POST["description"];
    $status      = $_POST["status"];

    // UPDATE supplier_paid
    $updateQuery = "
        UPDATE supplier_paid SET
            supplier_name   = '$supplier',
            supplier_amount = '$amount',
            status          = '$status',
            description     = '$description',
            date_time       = '$date_time',
            user_name       = '$userName',
            user_role       = '$userRole',
            outlet_name     = '$outlet_name',
            outlet_address  = '$outlet_address'
        WHERE id = '$id'
    ";

    if (mysqli_query($connection, $updateQuery)) {

        // ❗ SECOND UPDATE (AS-IT-IS)
        mysqli_query(
            $connection,
            "UPDATE supplier_closing 
             SET closing_balance = closing_balance - $amount
             WHERE supplier_name = '$supplier'"
        );

        echo "<script>
            Swal.fire({
                icon: 'success',
                title: 'Supplier payment updated successfully!',
                timer: 2000,
                showConfirmButton: false
            });
            setTimeout(() => {
                window.location.href = 'credit_pay.php';
            }, 2000);
        </script>";

    } else {
        echo "<script>
            Swal.fire({icon:'error', title:'Error!', text:'".mysqli_error($connection)."'});
        </script>";
    }
}
$payments = mysqli_query($connection, "SELECT * FROM supplier_paid where id = $id");

ob_end_flush();
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title><?php echo $tx; ?></title>

    <!-- CSS & Fonts -->
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
    <link href="../css/sb-admin-2.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <style>
        body {
            font-family: 'Quicksand', sans-serif;
        }
        .bg-gradient-primary {
            background: #0A4657;
            color: #fff;
        }
        .btn-primary {
            background: #0A4657;
            border: 1px solid #0A4657;
        }
        .btn-primary:hover {
            background: #fff;
            color: #0A4657;
        }
        .scroll-table {
            max-height: 400px;
            overflow-y: auto;
            display: block;
        }
        .btn, .form-control, option{
            font-weight:700;
        }
    </style>
</head>

<body id="page-top">

<div id="wrapper">
    <!-- Sidebar -->
    <?php include("common/sd.php"); ?>
    <!-- End of Sidebar -->

    <div id="content-wrapper" class="d-flex flex-column">
        <div id="content">

            <!-- Topbar -->
            <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">
                <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
                    <i class="fa fa-bars"></i>
                </button>
                <?php include('common/log.php'); ?>
            </nav>

            <!-- Page Content -->
<div class="container-fluid">
    <div class="row">
        <div class="col-9">
            <h3 class="font-weight-bold" style="color:#000;">Update Supplier Payment</h3>
        </div>
        <div class="col-3">
            <a href="credit_pay.php" style="float:right;" class="btn btn-dark"><i class="fas fa-arrow-left fa-1x"></i></a>
        </div>
       
        <div class="col-3"></div>
        <div class="col-6">
             <br><br>
            <div class="card shadow-sm mb-4">
    <div class="card-header bg-dark text-white font-weight-bold">
        Update Supplier Payment
    </div>
<?php
 $row = mysqli_fetch_array($payments);
?>
    <div class="card-body">
        <form method="post">

            <!-- Hidden ID -->
            <input type="hidden" name="paid_id" value="<?= $row['id']; ?>">

            <div class="form-group mb-3">
                <label>Date</label>
                <input type="date" name="date_time" class="form-control"
                       value="<?= $row['date_time']; ?>">
            </div>

            <div class="form-group mb-3">
                <label>Supplier Name</label>
                <input type="text" name="supplier_name" class="form-control"
                       value="<?= $row['supplier_name']; ?>" readonly>
            </div>

            <div class="form-group mb-3">
                <label>Amount</label>
                <input type="number" name="supplier_amount" class="form-control"
                       value="<?= $row['supplier_amount']; ?>">
            </div>

            <div class="form-group mb-3">
                <label>Status</label>
                <select name="status" class="form-control">
                    <option value="paid"   <?= ($row['status']=='paid')?'selected':'' ?>>Paid</option>
                    <option value="unpaid" <?= ($row['status']=='unpaid')?'selected':'' ?>>Unpaid</option>
                </select>
            </div>

            <div class="form-group mb-4">
                <label>Description</label>
                <input type="text" name="description" class="form-control"
                       value="<?= $row['description']; ?>">
            </div>

            <button type="submit" name="supplier_paid" class="btn btn-primary w-100">
                Update Payment
            </button>

        </form>
    </div>
</div>

        </div>
        <div class="col-3">
            
        </div>
    </div>
</div>
        </div>

        <!-- Footer -->
        <?php include("common/main_ft.php"); ?>
    </div>
</div>

<!-- Scripts -->
<script src="../vendor/jquery/jquery.min.js"></script>
<script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../vendor/jquery-easing/jquery.easing.min.js"></script>
<script src="../js/sb-admin-2.min.js"></script>

</body>
</html>