<?php
require_once __DIR__ . '/../../classes/Branding.php';
$companyName = Branding::companyName();
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Order.php';
require_once __DIR__ . '/../../includes/payment_options.php';

$database = new Database();
$conn     = $database->getConnection();
$auth     = new Auth($conn);
$orderObj = new Order($conn);

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

$orderId  = isset($_GET['order_id']) ? (int)$_GET['order_id'] : 0;
$order    = $orderObj->getOrderById($orderId);

if (!$order) {
    header('Location: list_orders.php?error=' . urlencode('Order not found.'));
    exit();
}

$isSuperAdmin = $auth->isSuperAdmin($_SESSION['user_id']);
$userBranchId = $auth->getUserBranch($_SESSION['user_id']);

if (!$isSuperAdmin && (int)$userBranchId !== (int)$order['branch_id']) {
    header('Location: list_orders.php?branch_id=' . $order['branch_id'] . '&error=' . urlencode('Access denied.'));
    exit();
}

if (!empty($order['assigned_code'])) {
    header('Location: order_details.php?order_id=' . $orderId . '&error=' . urlencode('This order is already completed.'));
    exit();
}

$totalPaid = $orderObj->getTotalPaid($orderId);
$balance   = round((float)$order['price'] - $totalPaid, 2);

if ($balance <= 0) {
    header('Location: order_details.php?order_id=' . $orderId . '&error=' . urlencode('Balance is already zero. Use the completion form to assign a code.'));
    exit();
}

$error   = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $amount        = round((float)($_POST['amount'] ?? 0), 2);
    $paymentMethod = normalizePaymentMethodValue($_POST['payment_method'] ?? 'cash');
    $notes         = trim($_POST['notes'] ?? '');
    $userId        = (int)$_SESSION['user_id'];

    if ($amount <= 0) {
        $error = 'Payment amount must be greater than zero.';
    } elseif ($amount > $balance + 0.01) {
        $error = 'Payment amount (MWK ' . number_format($amount, 2) . ') exceeds the remaining balance (MWK ' . number_format($balance, 2) . ').';
    } else {
        if ($orderObj->recordPayment($orderId, $amount, $paymentMethod, $notes, $userId)) {
            $newBalance = round($balance - $amount, 2);
            if ($newBalance <= 0.009) {
                header('Location: order_details.php?order_id=' . $orderId . '&success=' . urlencode('Final payment recorded. Please assign a unique code to complete the order.'));
            } else {
                header('Location: order_details.php?order_id=' . $orderId . '&success=' . urlencode('Payment of MWK ' . number_format($amount, 2) . ' recorded. Remaining balance: MWK ' . number_format($newBalance, 2) . '.'));
            }
            exit();
        } else {
            $error = 'Failed to record payment. Please try again.';
        }
    }
}
?>
<?php include __DIR__ . '/../../includes/header.php'; ?>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .page-card {
            max-width: 700px;
            margin: 0 auto;
            background: #fff;
            border-radius: 15px;
            box-shadow: 0 20px 60px rgba(0,0,0,.12);
            overflow: hidden;
            animation: slideUp .5s ease-out;
        }
        @keyframes slideUp {
            from { opacity:0; transform:translateY(25px); }
            to   { opacity:1; transform:translateY(0); }
        }
        .page-header {
            background: linear-gradient(45deg, #27ae60, #229954);
            color: #fff;
            padding: 28px 30px;
        }
        .page-header h2 { margin: 0; font-size: 22px; font-weight: 700; }
        .page-header .order-meta { font-size: 13px; opacity: .85; margin-top: 6px; }
        .page-body { padding: 35px; }
        .summary-bar {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 12px;
            margin-bottom: 28px;
        }
        .summary-item {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 16px;
            text-align: center;
            border-top: 3px solid #dee2e6;
        }
        .summary-item.balance { border-top-color: #e74c3c; }
        .summary-item.paid    { border-top-color: #27ae60; }
        .summary-item.total   { border-top-color: #3498db; }
        .summary-label { font-size: 11px; font-weight: 600; color: #6c757d; text-transform: uppercase; letter-spacing: .5px; }
        .summary-value { font-size: 20px; font-weight: 700; color: #2c3e50; margin-top: 4px; }
        .summary-item.balance .summary-value { color: #e74c3c; }
        .summary-item.paid    .summary-value { color: #27ae60; }
        .form-section {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 24px;
            border-left: 4px solid #27ae60;
            margin-bottom: 20px;
        }
        .form-label { font-weight: 600; color: #2c3e50; margin-bottom: 6px; }
        .form-control { border: 2px solid #e9ecef; border-radius: 8px; padding: 10px 14px; }
        .form-control:focus { border-color: #27ae60; box-shadow: 0 0 0 3px rgba(39,174,96,.1); }
        .btn-record {
            background: linear-gradient(45deg, #27ae60, #229954);
            color: #fff;
            border: none;
            padding: 12px 28px;
            border-radius: 8px;
            font-weight: 600;
            font-size: 15px;
            cursor: pointer;
            transition: all .2s;
        }
        .btn-record:hover { transform: translateY(-2px); box-shadow: 0 8px 20px rgba(39,174,96,.3); }
        .btn-back {
            background: #95a5a6;
            color: #fff;
            border: none;
            padding: 12px 24px;
            border-radius: 8px;
            font-weight: 600;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            transition: background .2s;
        }
        .btn-back:hover { background: #7f8c8d; color: #fff; text-decoration: none; }
        .alert { border-radius: 8px; padding: 14px 18px; }
        #amountHelp { font-size: 12px; color: #6c757d; margin-top: 4px; }
    </style>
<div class="page-card">
    <div class="page-header">
        <h2><i class="fas fa-money-bill-wave me-2"></i>Record Payment</h2>
        <div class="order-meta">
            Order #<?php echo htmlspecialchars($order['order_number']); ?> &mdash;
            <?php echo htmlspecialchars($order['customer_name']); ?> &mdash;
            <?php echo htmlspecialchars($order['item_name']); ?>
        </div>
    </div>

    <div class="page-body">
        <?php if ($error): ?>
            <div class="alert alert-danger"><i class="fas fa-exclamation-circle me-2"></i><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <div class="summary-bar">
            <div class="summary-item total">
                <div class="summary-label">Order Total</div>
                <div class="summary-value">MWK <?php echo number_format($order['price'], 2); ?></div>
            </div>
            <div class="summary-item paid">
                <div class="summary-label">Total Paid</div>
                <div class="summary-value">MWK <?php echo number_format($totalPaid, 2); ?></div>
            </div>
            <div class="summary-item balance">
                <div class="summary-label">Balance Due</div>
                <div class="summary-value">MWK <?php echo number_format($balance, 2); ?></div>
            </div>
        </div>

        <form method="POST" id="paymentForm">
            <div class="form-section">
                <div class="form-group">
                    <label class="form-label"><i class="fas fa-money-bill me-1"></i>Payment Amount (MWK) <span class="text-danger">*</span></label>
                    <input type="number" name="amount" id="amount" class="form-control"
                           step="0.01" min="0.01" max="<?php echo $balance; ?>"
                           value="<?php echo htmlspecialchars($_POST['amount'] ?? $balance); ?>" required autofocus>
                    <div id="amountHelp">Max: MWK <?php echo number_format($balance, 2); ?></div>
                </div>

                <div class="form-group">
                    <label class="form-label"><i class="fas fa-credit-card me-1"></i>Payment Method <span class="text-danger">*</span></label>
                    <select name="payment_method" class="form-control" required>
                        <?php echo paymentMethodSelectOptions($_POST['payment_method'] ?? 'cash'); ?>
                    </select>
                </div>

                <div class="form-group mb-0">
                    <label class="form-label"><i class="fas fa-sticky-note me-1"></i>Notes</label>
                    <input type="text" name="notes" class="form-control"
                           placeholder="e.g. Partial payment – balance due on delivery"
                           value="<?php echo htmlspecialchars($_POST['notes'] ?? ''); ?>">
                </div>
            </div>

            <div class="d-flex justify-content-between align-items-center">
                <a href="order_details.php?order_id=<?php echo $orderId; ?>" class="btn-back">
                    <i class="fas fa-arrow-left"></i> Back
                </a>
                <button type="submit" class="btn-record">
                    <i class="fas fa-check me-2"></i>Record Payment
                </button>
            </div>
        </form>
    </div>
</div>

<script>
    const balance = <?php echo $balance; ?>;
    document.getElementById('amount').addEventListener('input', function() {
        const val = parseFloat(this.value) || 0;
        const remaining = Math.max(0, balance - val);
        document.getElementById('amountHelp').textContent =
            'Max: MWK <?php echo number_format($balance, 2); ?>' +
            (val > 0 ? ' | After this payment: MWK ' + remaining.toLocaleString('en-MW', {minimumFractionDigits:2, maximumFractionDigits:2}) + ' remaining' : '');
    });
</script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
