<?php
session_start();
include 'layouts/dbconn.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if ($user_details) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $full_name = $user_details['full_name'];
}

// Handle payment processing
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['process_payment'])) {
    $invoice_id = $_POST['invoice_id'];
    $amount = $_POST['amount'];
    $payment_method = $_POST['payment_method'];
    $reference_number = $_POST['reference_number'];
    $notes = $_POST['notes'];
    
    // Generate payment number
    $payment_number = 'PAY' . date('Y') . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
    
    // Insert payment
    $sql_payment = "INSERT INTO payments (payment_number, invoice_id, customer_id, payment_date, payment_method, amount, reference_number, notes, created_by) 
                    SELECT ?, ?, customer_id, CURDATE(), ?, ?, ?, ?, ?
                    FROM invoices WHERE invoice_id = ?";
    $stmt_payment = $conn->prepare($sql_payment);
    $stmt_payment->bind_param("sisdsisi", $payment_number, $invoice_id, $payment_method, $amount, $reference_number, $notes, $user_id, $invoice_id);
    
    if ($stmt_payment->execute()) {
        // Update invoice paid amount
        $sql_update = "UPDATE invoices SET paid_amount = paid_amount + ?, balance_amount = total_amount - (paid_amount + ?), status = CASE WHEN (paid_amount + ?) >= total_amount THEN 'PAID' WHEN (paid_amount + ?) > 0 THEN 'PARTIAL' ELSE status END WHERE invoice_id = ?";
        $stmt_update = $conn->prepare($sql_update);
        $stmt_update->bind_param("ddddi", $amount, $amount, $amount, $amount, $invoice_id);
        $stmt_update->execute();
        
        $success_message = "Payment processed successfully!";
    } else {
        $error_message = "Error processing payment: " . $conn->error;
    }
}

// Get unpaid and partially paid invoices
$sql_outstanding = "SELECT i.*, c.first_name, c.last_name, c.company_name, c.customer_type
                    FROM invoices i
                    LEFT JOIN customers c ON i.customer_id = c.customer_id
                    WHERE i.status IN ('SENT', 'PARTIAL', 'OVERDUE') AND i.balance_amount > 0
                    ORDER BY i.due_date ASC
                    LIMIT 20";
$outstanding_invoices = $conn->query($sql_outstanding);

// Get recent payments today
$sql_recent = "SELECT p.*, i.invoice_number, c.first_name, c.last_name, c.company_name, c.customer_type
               FROM payments p
               LEFT JOIN invoices i ON p.invoice_id = i.invoice_id
               LEFT JOIN customers c ON p.customer_id = c.customer_id
               WHERE DATE(p.payment_date) = CURDATE()
               ORDER BY p.created_at DESC
               LIMIT 10";
$recent_payments = $conn->query($sql_recent);

// Get payment methods statistics
$sql_methods = "SELECT payment_method, COUNT(*) as count, SUM(amount) as total
                FROM payments 
                WHERE payment_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
                GROUP BY payment_method
                ORDER BY total DESC";
$payment_methods = $conn->query($sql_methods);

$conn->close();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Process Payments - Freight Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
    <!-- SweetAlert2 CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <!-- Remix Icons -->
    <link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
    
    <style>
        .page-content {
            padding: 1.5rem;
        }
        
        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .card {
            border: none;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
            border-radius: 10px;
        }
        
        .card-header {
            background: linear-gradient(45deg, #f8f9fa, #e9ecef);
            border-bottom: 1px solid #dee2e6;
            border-radius: 10px 10px 0 0;
        }
        
        .btn {
            border-radius: 8px;
            font-weight: 500;
        }
        
        .table th {
            background-color: #f8f9fa;
            font-weight: 600;
            border-top: none;
        }
        
        .badge {
            font-size: 0.75rem;
            padding: 0.5rem 0.75rem;
            border-radius: 6px;
        }
        
        .payment-form {
            background: #f8f9fa;
            padding: 1.5rem;
            border-radius: 10px;
            margin-bottom: 2rem;
        }
        
        .currency-input {
            position: relative;
        }
        
        .currency-symbol {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            font-weight: bold;
            color: #495057;
        }
        
        .currency-input input {
            padding-left: 40px;
        }
        
        .status-paid { background-color: #28a745; }
        .status-partial { background-color: #ffc107; color: #000; }
        .status-sent { background-color: #17a2b8; }
        .status-overdue { background-color: #dc3545; }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Process Payments</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item active">Process Payments</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Success/Error Messages -->
                    <?php if (isset($success_message)): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="ri-check-line align-middle me-2"></i>
                        <?php echo $success_message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <?php if (isset($error_message)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="ri-error-warning-line align-middle me-2"></i>
                        <?php echo $error_message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <!-- Stats Cards -->
                    <div class="row">
                        <div class="col-xl-3 col-md-6">
                            <div class="card">
                                <div class="card-body">
                                    <div class="d-flex">
                                        <div class="flex-1">
                                            <h5 class="text-muted mb-1">Outstanding Invoices</h5>
                                            <h4 class="mb-0"><?php echo $outstanding_invoices->num_rows; ?></h4>
                                        </div>
                                        <div class="avatar-sm">
                                            <span class="avatar-title bg-warning rounded">
                                                <i class="ri-file-text-line fs-4"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="card">
                                <div class="card-body">
                                    <div class="d-flex">
                                        <div class="flex-1">
                                            <h5 class="text-muted mb-1">Today's Payments</h5>
                                            <h4 class="mb-0"><?php echo $recent_payments->num_rows; ?></h4>
                                        </div>
                                        <div class="avatar-sm">
                                            <span class="avatar-title bg-success rounded">
                                                <i class="ri-money-dollar-circle-line fs-4"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="card">
                                <div class="card-body">
                                    <div class="d-flex">
                                        <div class="flex-1">
                                            <h5 class="text-muted mb-1">Payment Methods</h5>
                                            <h4 class="mb-0"><?php echo $payment_methods->num_rows; ?></h4>
                                        </div>
                                        <div class="avatar-sm">
                                            <span class="avatar-title bg-info rounded">
                                                <i class="ri-bank-card-line fs-4"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="card">
                                <div class="card-body">
                                    <div class="d-flex">
                                        <div class="flex-1">
                                            <h5 class="text-muted mb-1">Quick Actions</h5>
                                            <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#quickPaymentModal">
                                                <i class="ri-add-line"></i> Quick Payment
                                            </button>
                                        </div>
                                        <div class="avatar-sm">
                                            <span class="avatar-title bg-primary rounded">
                                                <i class="ri-flashlight-line fs-4"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Outstanding Invoices -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">
                                        <i class="ri-file-list-line me-2"></i>Outstanding Invoices
                                    </h4>
                                </div>
                                <div class="card-body">
                                    <table id="invoicesTable" class="table table-striped table-hover dt-responsive nowrap w-100">
                                        <thead>
                                            <tr>
                                                <th>Invoice #</th>
                                                <th>Customer</th>
                                                <th>Date</th>
                                                <th>Due Date</th>
                                                <th>Total</th>
                                                <th>Paid</th>
                                                <th>Balance</th>
                                                <th>Status</th>
                                                <th>Action</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php while ($invoice = $outstanding_invoices->fetch_assoc()): ?>
                                            <tr>
                                                <td><strong><?php echo $invoice['invoice_number']; ?></strong></td>
                                                <td>
                                                    <?php 
                                                    if ($invoice['customer_type'] === 'CORPORATE') {
                                                        echo $invoice['company_name'];
                                                    } else {
                                                        echo $invoice['first_name'] . ' ' . $invoice['last_name'];
                                                    }
                                                    ?>
                                                </td>
                                                <td><?php echo date('M j, Y', strtotime($invoice['invoice_date'])); ?></td>
                                                <td><?php echo date('M j, Y', strtotime($invoice['due_date'])); ?></td>
                                                <td><strong><?php echo number_format($invoice['total_amount'], 2); ?></strong></td>
                                                <td><?php echo number_format($invoice['paid_amount'], 2); ?></td>
                                                <td><strong class="text-danger"><?php echo number_format($invoice['balance_amount'], 2); ?></strong></td>
                                                <td>
                                                    <span class="badge status-<?php echo strtolower($invoice['status']); ?>">
                                                        <?php echo $invoice['status']; ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <button type="button" class="btn btn-primary btn-sm" onclick="processPayment(<?php echo $invoice['invoice_id']; ?>, '<?php echo $invoice['invoice_number']; ?>', <?php echo $invoice['balance_amount']; ?>, '<?php echo $invoice['customer_type'] === 'CORPORATE' ? $invoice['company_name'] : $invoice['first_name'] . ' ' . $invoice['last_name']; ?>')">
                                                        <i class="ri-money-dollar-circle-line"></i> Pay
                                                    </button>
                                                </td>
                                            </tr>
                                            <?php endwhile; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Recent Payments -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">
                                        <i class="ri-history-line me-2"></i>Today's Payments
                                    </h4>
                                </div>
                                <div class="card-body">
                                    <table class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>Payment #</th>
                                                <th>Invoice</th>
                                                <th>Customer</th>
                                                <th>Method</th>
                                                <th>Amount</th>
                                                <th>Reference</th>
                                                <th>Time</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php while ($payment = $recent_payments->fetch_assoc()): ?>
                                            <tr>
                                                <td><strong><?php echo $payment['payment_number']; ?></strong></td>
                                                <td><?php echo $payment['invoice_number']; ?></td>
                                                <td>
                                                    <?php 
                                                    if ($payment['customer_type'] === 'CORPORATE') {
                                                        echo $payment['company_name'];
                                                    } else {
                                                        echo $payment['first_name'] . ' ' . $payment['last_name'];
                                                    }
                                                    ?>
                                                </td>
                                                <td><?php echo $payment['payment_method']; ?></td>
                                                <td><strong><?php echo number_format($payment['amount'], 2); ?></strong></td>
                                                <td><?php echo $payment['reference_number']; ?></td>
                                                <td><?php echo date('H:i', strtotime($payment['created_at'])); ?></td>
                                            </tr>
                                            <?php endwhile; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Payment Modal -->
    <div class="modal fade" id="paymentModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Process Payment</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="invoice_id" id="invoice_id">
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Invoice Number</label>
                                    <input type="text" class="form-control" id="invoice_number" readonly>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Customer</label>
                                    <input type="text" class="form-control" id="customer_name" readonly>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Outstanding Balance</label>
                                    <input type="text" class="form-control" id="balance_amount" readonly>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Payment Amount *</label>
                                    <div class="currency-input">
                                        <span class="currency-symbol">KSh</span>
                                        <input type="number" class="form-control" name="amount" id="payment_amount" step="0.01" required>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Payment Method *</label>
                                    <select class="form-control" name="payment_method" required>
                                        <option value="">Select Method</option>
                                        <option value="CASH">Cash</option>
                                        <option value="BANK_TRANSFER">Bank Transfer</option>
                                        <option value="CARD">Credit/Debit Card</option>
                                        <option value="MOBILE_MONEY">Mobile Money</option>
                                        <option value="CHEQUE">Cheque</option>
                                        <option value="OTHER">Other</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Reference Number</label>
                                    <input type="text" class="form-control" name="reference_number" placeholder="Transaction reference">
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Notes</label>
                            <textarea class="form-control" name="notes" rows="3" placeholder="Payment notes or remarks"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" name="process_payment" class="btn btn-primary">
                            <i class="ri-money-dollar-circle-line"></i> Process Payment
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <!-- DataTables JS -->
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    
    <!-- SweetAlert2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
        $(document).ready(function() {
            // Initialize DataTables
            $('#invoicesTable').DataTable({
                responsive: true,
                pageLength: 25,
                order: [[3, 'asc']], // Sort by due date
                columnDefs: [
                    { targets: [4, 5, 6], className: 'text-end' },
                    { targets: [8], orderable: false }
                ]
            });
        });
        
        function processPayment(invoiceId, invoiceNumber, balanceAmount, customerName) {
            $('#invoice_id').val(invoiceId);
            $('#invoice_number').val(invoiceNumber);
            $('#customer_name').val(customerName);
            $('#balance_amount').val('KSh ' + balanceAmount.toFixed(2));
            $('#payment_amount').val(balanceAmount.toFixed(2));
            $('#payment_amount').attr('max', balanceAmount);
            $('#paymentModal').modal('show');
        }
        
        // Validate payment amount
        $('#payment_amount').on('input', function() {
            const amount = parseFloat($(this).val());
            const maxAmount = parseFloat($(this).attr('max'));
            
            if (amount > maxAmount) {
                $(this).addClass('is-invalid');
                $(this).siblings('.invalid-feedback').remove();
                $(this).after('<div class="invalid-feedback">Amount cannot exceed outstanding balance</div>');
            } else {
                $(this).removeClass('is-invalid');
                $(this).siblings('.invalid-feedback').remove();
            }
        });
        
        // Show success message with SweetAlert
        <?php if (isset($success_message)): ?>
        Swal.fire({
            icon: 'success',
            title: 'Success!',
            text: '<?php echo $success_message; ?>',
            timer: 3000,
            showConfirmButton: false
        });
        <?php endif; ?>
    </script>
    
    <script src="assets/js/app.js"></script>
</body>
</html>