<?php
session_start();
require("php_con.php");
require("check_user.php");
require("function.php");

// Handle supplier ID from URL
if(isset($_GET['sp_supplier_id'])) {
    if($_GET['sp_supplier_id'] == "") {
        echo "<script>window.location='supplier-payment';</script>";
    }
    
    $supplier_id = mysqli_real_escape_string($connation, $_GET['sp_supplier_id']);
    $sup_query = mysqli_query($connation, "SELECT * FROM supplier_details WHERE supplier_id='$supplier_id'");
    $sup_result = mysqli_fetch_assoc($sup_query);
}

// Handle payment record removal
if(isset($_GET['remove'])) {
    $sp_id = mysqli_real_escape_string($connation, $_GET['remove']);
    if(mysqli_query($connation, "DELETE FROM supplier_payment WHERE sp_id='$sp_id'")) {
        echo "<script>window.location='supplier-payment?removed';</script>";
    }
}

// Set default date range
$f_date = date("Y-m-d", strtotime($current_date." -10 day"));
$t_date = date("Y-m-t");

// Handle payment form submission
if(isset($_POST['pay_btn'])) {
    $sp_supplier_id = mysqli_real_escape_string($connation, $_POST['sp_supplier_id']);
    $sp_payment_info = mysqli_real_escape_string($connation, $_POST['sp_payment_info']);
    $sp_amount = mysqli_real_escape_string($connation, $_POST['sp_amount']);
    
    if(mysqli_query($connation, "INSERT INTO supplier_payment 
        (sp_id, sp_supplier_id, sp_pay_user, sp_payment_info, sp_amount, sp_add_date, sp_add_time)
        VALUES 
        (NULL, '$sp_supplier_id', '$_COOKIE[user_id]', '$sp_payment_info', '$sp_amount', '$current_date', '$current_time')")) {
        echo "<script>window.location='supplier-payment?sp_supplier_id=$sp_supplier_id';</script>";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" href="favicon.ico">
    <title><?php echo $system_name; ?> - Supplier Payment</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    
    <!-- Select2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet">
    
    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap5.min.css">
    
    <!-- Custom CSS -->
    <style>
        :root {
            --primary-color: #4e73df;
            --secondary-color: #858796;
            --success-color: #1cc88a;
            --info-color: #36b9cc;
            --warning-color: #f6c23e;
            --danger-color: #e74a3b;
            --light-color: #f8f9fc;
            --dark-color: #5a5c69;
        }
        
        body {
            font-family: 'Nunito', sans-serif;
            background-color: #f8f9fc;
            color: #333;
        }
        
        .preloader {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.9);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }
        
        .container-fluid {
            padding: 1.5rem;
        }
        
        .card {
            border: none;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15);
            border-radius: 0.35rem;
            margin-bottom: 1.5rem;
        }
        
        .card-header {
            background-color: #f8f9fc;
            border-bottom: 1px solid #e3e6f0;
            padding: 1rem;
            font-weight: 700;
        }
        
        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
        
        .btn-success {
            background-color: var(--success-color);
            border-color: var(--success-color);
        }
        
        .btn-danger {
            background-color: var(--danger-color);
            border-color: var(--danger-color);
        }
        
        .table thead th {
            vertical-align: bottom;
            border-bottom: 2px solid #e3e6f0;
            font-weight: 700;
            color: var(--dark-color);
        }
        
        .table-hover tbody tr:hover {
            background-color: rgba(78, 115, 223, 0.05);
        }
        
        .select2-container .select2-selection--single {
            height: 38px;
            padding: 0.375rem 0.75rem;
        }
        
        .breadcrumb {
            background-color: transparent;
            padding: 0;
            margin-bottom: 1rem;
        }
        
        .summary-card {
            border-left: 0.25rem solid;
        }
        
        .info-card {
            border-left-color: var(--info-color);
        }
        
        .success-card {
            border-left-color: var(--success-color);
        }
        
        .danger-card {
            border-left-color: var(--danger-color);
        }
        
        .badge-action {
            cursor: pointer;
            padding: 0.5rem;
            margin-right: 0.25rem;
        }
        
        .payment-form-card {
            background-color: rgba(78, 115, 223, 0.05);
        }
    </style>
</head>

<body>
    <!-- Preloader -->
    <div id="preloader" class="preloader">
        <img src="image/loading.gif" alt="Loading..." width="80">
    </div>
    
    <!-- Header -->
    <?php require("header.php"); ?>
    
    <div class="container-fluid">
        <div class="d-sm-flex align-items-center justify-content-between mb-4">
            <h1 class="h3 mb-0 text-gray-800">Supplier Payment Management</h1>
            
            <!-- Breadcrumb -->
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb m-0">
                    <li class="breadcrumb-item"><a href="dashboard">Dashboard</a></li>
                    <li class="breadcrumb-item"><a href="supplier">Supplier</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Payments</li>
                </ol>
            </nav>
        </div>
        
        <!-- Supplier Submenu -->
        <div class="mb-4">
            <?php require("sub_menu/supplier.php"); ?>
        </div>
        
        <!-- Supplier Selection Card -->
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <i class="fas fa-user-tie me-2"></i> Select Supplier
            </div>
            <div class="card-body">
                <form method="post" autocomplete="off">
                    <div class="form-group">
                        <select name="sp_supplier_id" id="sp_supplier_id" class="form-control select2" required onChange="window.location='supplier-payment?sp_supplier_id='+this.value;">
                            <option value="" hidden>Select Supplier</option>
                            <?php 
                            $supplier_query = mysqli_query($connation, "SELECT * FROM supplier_details ORDER BY supplier_name");
                            while($supplier_result = mysqli_fetch_array($supplier_query)) {    
                            ?>
                            <option <?php if(isset($_GET['sp_supplier_id'])){ if($_GET['sp_supplier_id'] == $supplier_result['supplier_id']){echo "selected";} } ?> value="<?php echo $supplier_result['supplier_id']; ?>">
                                <?php echo $supplier_result['supplier_name']; ?> (<?php echo "0".(int)$supplier_result['supplier_mobile']; ?>)
                            </option>
                            <?php } ?>
                        </select>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- Supplier Details and Payment Section -->
        <div class="row">
            <!-- Supplier Details -->
            <div class="col-md-4">
                <div class="card shadow h-100">
                    <div class="card-header">
                        <i class="fas fa-info-circle me-2"></i> Supplier Details
                    </div>
                    <div class="card-body">
                        <table class="table table-borderless">
                            <tbody>
                                <tr>
                                    <th class="text-muted">Name</th>
                                    <td class="text-capitalize"><?php if(isset($_GET['sp_supplier_id'])){ echo $sup_result['supplier_name']; } else { echo "-"; } ?></td>
                                </tr>
                                <tr>
                                    <th class="text-muted">Mobile</th>
                                    <td><?php if(isset($_GET['sp_supplier_id'])){ echo "0".(int)$sup_result['supplier_mobile']; } else { echo "-"; } ?></td>
                                </tr>
                                <tr>
                                    <th class="text-muted">Company</th>
                                    <td class="text-capitalize"><?php if(isset($_GET['sp_supplier_id'])){ echo $sup_result['supplier_company']; } else { echo "-"; } ?></td>
                                </tr>
                                <tr>
                                    <th class="text-muted">Address</th>
                                    <td style="white-space: pre-line;"><?php if(isset($_GET['sp_supplier_id'])){ echo $sup_result['supplier_address']; } else { echo "-"; } ?></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
            <!-- Payment Summary -->
            <div class="col-md-4">
                <div class="card shadow h-100">
                    <div class="card-header">
                        <i class="fas fa-chart-pie me-2"></i> Payment Summary
                    </div>
                    <div class="card-body">
                        <div class="row no-gutters align-items-center mb-3">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-info text-uppercase mb-1">Total Invoices</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">
                                    <?php if(isset($_GET['sp_supplier_id'])){ echo number_format((float)supplier_total_invoice_amount($sup_result['supplier_id']), 2); } else { echo "0.00"; } ?>
                                </div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-file-invoice-dollar fa-2x text-info"></i>
                            </div>
                        </div>
                        
                        <div class="row no-gutters align-items-center mb-3">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Total Payments</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">
                                    <?php if(isset($_GET['sp_supplier_id'])){ echo number_format((float)supplier_total_payment($sup_result['supplier_id']), 2); } else { echo "0.00"; } ?>
                                </div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-money-bill-wave fa-2x text-success"></i>
                            </div>
                        </div>
                        
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-danger text-uppercase mb-1">Due Balance</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">
                                    <?php if(isset($_GET['sp_supplier_id'])){ echo number_format((float)supplier_total_invoice_amount($sup_result['supplier_id']) - supplier_total_payment($sup_result['supplier_id']), 2); } else { echo "0.00"; } ?>
                                </div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-balance-scale fa-2x text-danger"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Last 5 Payments -->
            <div class="col-md-4">
                <div class="card shadow h-100">
                    <div class="card-header">
                        <i class="fas fa-history me-2"></i> Last 5 Payments
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-sm table-hover mb-0">
                                <thead class="bg-light">
                                    <tr>
                                        <th>Date & Time</th>
                                        <th>User</th>
                                        <th class="text-end">Amount</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    if(isset($_GET['sp_supplier_id'])) {
                                        $lp_query = mysqli_query($connation, "SELECT sp.*, CONCAT(ud.user_fname,' ',ud.user_lname) AS u_name
                                        FROM supplier_payment sp 
                                        INNER JOIN user_details ud ON sp.sp_pay_user = ud.user_id
                                        WHERE sp.sp_supplier_id = '$sup_result[supplier_id]'
                                        ORDER BY sp.sp_id DESC
                                        LIMIT 5");
                                        
                                        if(mysqli_num_rows($lp_query) > 0) {
                                            while($lp_result = mysqli_fetch_assoc($lp_query)) {
                                    ?>
                                    <tr>
                                        <td><?php echo date("Y-m-d h:i A", strtotime($lp_result['sp_add_date']." ".$lp_result['sp_add_time'])); ?></td>
                                        <td><?php echo $lp_result['u_name']; ?></td>
                                        <td class="text-end fw-bold"><?php echo number_format((float)$lp_result['sp_amount'], 2); ?></td>
                                    </tr>
                                    <?php
                                            }
                                        } else {
                                    ?>
                                    <tr>
                                        <td colspan="3" class="text-center py-3">No payment records found</td>
                                    </tr>
                                    <?php
                                        }
                                    } else {
                                    ?>
                                    <tr>
                                        <td colspan="3" class="text-center py-3">Select a supplier to view payment history</td>
                                    </tr>
                                    <?php } ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Payment Form -->
        <?php if(isset($_GET['sp_supplier_id'])){ ?>
        <div class="card shadow mt-4">
            <div class="card-header bg-success text-white">
                <i class="fas fa-money-bill-wave me-2"></i> Make Payment
            </div>
            <div class="card-body">
                <form method="post" autocomplete="off">
                    <input name="sp_supplier_id" type="hidden" id="sp_supplier_id" value="<?php echo $sup_result['supplier_id']; ?>">
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="sp_amount" class="form-label">Payment Amount <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fas fa-dollar-sign"></i></span>
                                    <input name="sp_amount" type="number" required class="form-control" id="sp_amount" min="1" step="0.01" placeholder="Enter amount">
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="sp_payment_info" class="form-label">Payment Remarks</label>
                                <textarea name="sp_payment_info" rows="3" class="form-control" id="sp_payment_info" placeholder="Enter payment details"><?php echo $current_date; ?> payment</textarea>
                            </div>
                        </div>
                    </div>
                    
                    <div class="d-flex justify-content-end mt-3">
                        <a href="supplier-payment" class="btn btn-light me-2">
                            <i class="fas fa-times"></i> Cancel
                        </a>
                        <button name="pay_btn" type="submit" class="btn btn-success">
                            <i class="fas fa-check"></i> Confirm Payment
                        </button>
                    </div>
                </form>
            </div>
        </div>
        <?php } ?>
        
        <!-- Payment History -->
        <div class="card shadow mt-4">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <i class="fas fa-history me-2"></i> Payment History
                    </div>
                    
                    <!-- Date Filter Form -->
                    <form method="post" autocomplete="off" class="d-flex align-items-center">
                        <div class="input-group input-group-sm me-2" style="width: 160px;">
                            <span class="input-group-text">From</span>
                            <input name="f_date" type="date" required class="form-control" id="f_date" value="<?php if(isset($_POST['f_date'])){ echo $_POST['f_date']; } else { echo $f_date; } ?>">
                        </div>
                        
                        <div class="input-group input-group-sm me-2" style="width: 160px;">
                            <span class="input-group-text">To</span>
                            <input name="t_date" type="date" required class="form-control" id="t_date" value="<?php if(isset($_POST['t_date'])){ echo $_POST['t_date']; } else { echo $t_date; } ?>">
                        </div>
                        
                        <button type="submit" class="btn btn-sm btn-primary">
                            <i class="fas fa-filter"></i> Filter
                        </button>
                    </form>
                </div>
            </div>
            
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover table-striped datatable" id="paymentDataTable">
                        <thead class="bg-light">
                            <tr>
                                <th width="50"><i class="fas fa-cog"></i></th>
                                <th>Supplier</th>
                                <th>Payment Info</th>
                                <th>Paid By</th>
                                <th>Date & Time</th>
                                <th class="text-end">Amount</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            if(isset($_POST['f_date']) && isset($_POST['t_date'])) {
                                $f_date = $_POST['f_date'];
                                $t_date = $_POST['t_date'];
                            }
                            
                            $payment_query = mysqli_query($connation, "SELECT sp.*, CONCAT(ud.user_fname,' ',ud.user_lname) AS u_name, spd.supplier_name
                            FROM supplier_payment sp 
                            INNER JOIN user_details ud ON sp.sp_pay_user = ud.user_id
                            LEFT JOIN supplier_details spd ON sp.sp_supplier_id = spd.supplier_id
                            WHERE sp.sp_add_date BETWEEN '$f_date' AND '$t_date'
                            ORDER BY sp.sp_id DESC");
                            
                            if(mysqli_num_rows($payment_query) > 0) {
                                while($payment_result = mysqli_fetch_array($payment_query)) {
                            ?>
                            <tr>
                                <td>
                                    <a href="supplier-payment?remove=<?php echo $payment_result['sp_id']; ?>" class="btn btn-sm btn-danger" 
                                       onclick="return confirm('Are you sure you want to remove this payment record?');">
                                        <i class="fas fa-trash-alt"></i>
                                    </a>
                                </td>
                                <td><?php echo $payment_result['supplier_name']; ?></td>
                                <td><?php echo $payment_result['sp_payment_info']; ?></td>
                                <td><?php echo $payment_result['u_name']; ?></td>
                                <td><?php echo date("Y-m-d h:i A", strtotime($payment_result['sp_add_date']." ".$payment_result['sp_add_time'])); ?></td>
                                <td class="text-end fw-bold"><?php echo number_format((float)$payment_result['sp_amount'], 2); ?></td>
                            </tr>
                            <?php
                                }
                            } else {
                            ?>
                            <tr>
                                <td colspan="6" class="text-center py-3">No payment records found in the selected date range</td>
                            </tr>
                            <?php } ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Footer -->
    <footer class="sticky-footer bg-white mt-4">
        <div class="container my-auto">
            <div class="copyright text-center my-auto">
                <span>Copyright &copy; <?php echo $system_name; ?> <?php echo date('Y'); ?></span>
            </div>
        </div>
    </footer>
    
    <!-- Scripts -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
    
    <script>
        // Remove preloader when page is loaded
        window.addEventListener("load", function() {
            var preloader = document.getElementById('preloader');
            preloader.style.display = 'none';
        });
        
        // Initialize Select2
        $(document).ready(function() {
            $('.select2').select2({
                placeholder: "Select a supplier",
                allowClear: true,
                theme: "bootstrap-5"
            });
            
            // Initialize DataTable
            $('#paymentDataTable').DataTable({
                pageLength: 10,
                lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                responsive: true,
                order: [[4, 'desc']]
            });
            
            // Show success message if removed parameter exists
            <?php if(isset($_GET['removed'])) { ?>
            setTimeout(function() {
                alert("Payment record has been removed successfully!");
            }, 500);
            <?php } ?>
        });
    </script>
</body>
</html>
<?php @mysqli_close($connation); ?>