<?php
session_start();
require_once 'db_connect.php';

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

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role'] ?? 'user';

// Only brokers and admins can manage payments
if(!in_array($user_role, ['broker', 'admin'])) {
    header('Location: dashboard.php?error=Access denied');
    exit;
}

$client_id = isset($_GET['client_id']) ? intval($_GET['client_id']) : 0;

if($client_id == 0) {
    header('Location: clients.php?error=Client ID required');
    exit;
}

// Get client details and verify access
$owner_check = $user_role == 'admin' ? "1=1" : "c.broker_id = $user_id";
$client_result = mysqli_query($conn, "SELECT c.*, u.full_name as broker_name
                                       FROM clients c
                                       JOIN users u ON c.broker_id = u.id
                                       WHERE c.id = $client_id AND $owner_check");

if(mysqli_num_rows($client_result) == 0) {
    header('Location: clients.php?error=Client not found or access denied');
    exit;
}

$client = mysqli_fetch_assoc($client_result);

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

// Get payment settings
$settings_result = mysqli_query($conn, "SELECT setting_key, setting_value FROM payment_settings");
$settings = [];
while($s = mysqli_fetch_assoc($settings_result)) {
    $settings[$s['setting_key']] = $s['setting_value'];
}
$yearly_fee = $settings['yearly_fee'] ?? 50000;
$grace_period = $settings['grace_period_days'] ?? 30;

// Handle payment actions
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $action = $_POST['action'] ?? '';

    if($action == 'add_payment') {
        $amount = floatval($_POST['amount']);
        $payment_year = intval($_POST['payment_year']);
        $payment_date = mysqli_real_escape_string($conn, $_POST['payment_date']);
        $payment_method = mysqli_real_escape_string($conn, $_POST['payment_method']);
        $reference_number = mysqli_real_escape_string($conn, trim($_POST['reference_number']));
        $receipt_number = mysqli_real_escape_string($conn, trim($_POST['receipt_number']));
        $notes = mysqli_real_escape_string($conn, trim($_POST['notes']));

        if($amount <= 0) {
            $error = 'Amount must be greater than zero';
        } elseif($payment_year < 2020 || $payment_year > 2050) {
            $error = 'Invalid payment year';
        } else {
            // Check if already paid for this year
            $check = mysqli_query($conn, "SELECT id FROM client_payments
                                          WHERE client_id = $client_id AND payment_year = $payment_year AND status = 'confirmed'");
            if(mysqli_num_rows($check) > 0) {
                $error = "Payment for year $payment_year already exists";
            } else {
                $status = $user_role == 'admin' ? 'confirmed' : 'pending';
                $confirmed_by = $user_role == 'admin' ? $user_id : 'NULL';

                $sql = "INSERT INTO client_payments (client_id, amount, payment_year, payment_date, payment_method,
                        reference_number, receipt_number, notes, status, recorded_by, confirmed_by)
                        VALUES ($client_id, $amount, $payment_year, '$payment_date', '$payment_method',
                        '$reference_number', '$receipt_number', '$notes', '$status', $user_id, $confirmed_by)";

                if(mysqli_query($conn, $sql)) {
                    // If payment confirmed, activate client
                    if($status == 'confirmed' && $payment_year >= date('Y')) {
                        mysqli_query($conn, "UPDATE clients SET access_status = 'active' WHERE id = $client_id");
                    }
                    $success = 'Payment recorded successfully';
                } else {
                    $error = 'Failed to record payment: ' . mysqli_error($conn);
                }
            }
        }
    }

    if($action == 'confirm_payment' && $user_role == 'admin') {
        $payment_id = intval($_POST['payment_id']);
        $sql = "UPDATE client_payments SET status = 'confirmed', confirmed_by = $user_id WHERE id = $payment_id";
        if(mysqli_query($conn, $sql)) {
            // Get payment year
            $p = mysqli_fetch_assoc(mysqli_query($conn, "SELECT payment_year FROM client_payments WHERE id = $payment_id"));
            if($p && $p['payment_year'] >= date('Y')) {
                mysqli_query($conn, "UPDATE clients SET access_status = 'active' WHERE id = $client_id");
            }
            $success = 'Payment confirmed';
        } else {
            $error = 'Failed to confirm payment';
        }
    }

    if($action == 'cancel_payment') {
        $payment_id = intval($_POST['payment_id']);
        // Verify ownership
        $check = mysqli_query($conn, "SELECT id FROM client_payments WHERE id = $payment_id AND (recorded_by = $user_id OR $user_id IN (SELECT id FROM users WHERE role = 'admin'))");
        if(mysqli_num_rows($check) > 0) {
            mysqli_query($conn, "UPDATE client_payments SET status = 'cancelled' WHERE id = $payment_id");
            $success = 'Payment cancelled';
        } else {
            $error = 'Cannot cancel this payment';
        }
    }
}

// Get payment history
$payments = mysqli_query($conn, "SELECT cp.*, u.full_name as recorded_by_name, u2.full_name as confirmed_by_name
                                  FROM client_payments cp
                                  JOIN users u ON cp.recorded_by = u.id
                                  LEFT JOIN users u2 ON cp.confirmed_by = u2.id
                                  WHERE cp.client_id = $client_id
                                  ORDER BY cp.payment_year DESC, cp.created_at DESC");

// Calculate payment status
$current_year = date('Y');
$paid_years = [];
$payments_arr = [];
while($p = mysqli_fetch_assoc($payments)) {
    $payments_arr[] = $p;
    if($p['status'] == 'confirmed') {
        $paid_years[] = $p['payment_year'];
    }
}
$is_current_year_paid = in_array($current_year, $paid_years);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Client Payments - <?php echo htmlspecialchars($client['full_name']); ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/font-awesome/css/all.min.css">
    <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <style>
        * { font-family: 'Inter', sans-serif; }
        :root { --primary: #1a3a6e; --secondary: #2d5a3d; --sidebar-width: 260px; }
        body { background: #f4f6f9; margin: 0; }
        .sidebar {
            width: var(--sidebar-width);
            height: 100vh;
            background: linear-gradient(180deg, var(--primary) 0%, var(--secondary) 100%);
            position: fixed;
            left: 0;
            top: 0;
            z-index: 1000;
        }
        .sidebar-header { padding: 20px; text-align: center; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .sidebar-header i { font-size: 40px; color: white; }
        .sidebar-header h4 { color: white; margin-top: 10px; font-size: 18px; }
        .sidebar-menu { padding: 20px 0; }
        .sidebar-menu a {
            display: flex; align-items: center; padding: 12px 25px;
            color: rgba(255,255,255,0.8); text-decoration: none; transition: all 0.3s;
        }
        .sidebar-menu a:hover, .sidebar-menu a.active { background: rgba(255,255,255,0.1); color: white; }
        .sidebar-menu a i { width: 25px; margin-right: 10px; }
        .main-content { margin-left: var(--sidebar-width); padding: 20px; min-height: 100vh; }
        .topbar {
            background: white; padding: 15px 25px; border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05); margin-bottom: 25px;
        }
        .card { border: none; border-radius: 15px; box-shadow: 0 5px 15px rgba(0,0,0,0.05); margin-bottom: 20px; }
        .card-header { background: white; border-bottom: 1px solid #eee; padding: 20px; font-weight: 600; }
        .btn-primary { background: var(--primary); border: none; }
        .btn-primary:hover { background: var(--secondary); }
        .stat-card {
            background: white;
            border-radius: 15px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
        }
        .stat-card.paid { border-left: 4px solid #28a745; }
        .stat-card.unpaid { border-left: 4px solid #dc3545; }
        .stat-card h3 { margin: 10px 0 5px; font-weight: 700; }
        .payment-timeline {
            position: relative;
            padding-left: 30px;
        }
        .payment-timeline::before {
            content: '';
            position: absolute;
            left: 10px;
            top: 0;
            bottom: 0;
            width: 2px;
            background: #ddd;
        }
        .payment-item {
            position: relative;
            margin-bottom: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 10px;
        }
        .payment-item::before {
            content: '';
            position: absolute;
            left: -24px;
            top: 20px;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: var(--primary);
        }
        .payment-item.confirmed::before { background: #28a745; }
        .payment-item.pending::before { background: #ffc107; }
        .payment-item.cancelled::before { background: #dc3545; }
        .mobile-menu-btn {
            display: none;
            position: fixed;
            top: 15px;
            left: 15px;
            z-index: 1001;
            background: var(--primary);
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 5px;
        }
        @media (max-width: 991px) {
            .sidebar { transform: translateX(-100%); transition: transform 0.3s; }
            .sidebar.active { transform: translateX(0); }
            .main-content { margin-left: 0 !important; padding: 15px; }
            .mobile-menu-btn { display: block; }
        }
    </style>
</head>
<body>
    <button class="mobile-menu-btn" onclick="toggleSidebar()">
        <i class="fas fa-bars"></i>
    </button>

    <nav class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <i class="fas fa-map-marked-alt"></i>
            <h4>Land Survey</h4>
        </div>
        <div class="sidebar-menu">
            <a href="dashboard.php"><i class="fas fa-home"></i> Dashboard</a>
            <a href="lands.php"><i class="fas fa-map"></i> My Lands</a>
            <a href="clients.php" class="active"><i class="fas fa-users"></i> My Clients</a>
            <?php if($user_role == 'admin'): ?>
            <a href="admin/dashboard.php"><i class="fas fa-cog"></i> Admin Panel</a>
            <?php endif; ?>
            <a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </div>
    </nav>

    <div class="main-content">
        <?php if($error): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <?php echo $error; ?>
            <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
        <?php endif; ?>

        <?php if($success): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <?php echo $success; ?>
            <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
        <?php endif; ?>

        <div class="topbar">
            <div class="d-flex justify-content-between align-items-center flex-wrap">
                <div>
                    <a href="clients.php" class="text-muted"><i class="fas fa-arrow-left mr-2"></i>Back to Clients</a>
                    <h5 class="mb-0 mt-2"><i class="fas fa-money-bill-wave mr-2"></i><?php echo htmlspecialchars($client['full_name']); ?></h5>
                    <small class="text-muted">Payment Management | Phone: <?php echo htmlspecialchars($client['phone']); ?></small>
                </div>
                <div class="mt-2">
                    <button class="btn btn-primary" data-toggle="modal" data-target="#addPaymentModal">
                        <i class="fas fa-plus mr-1"></i>Record Payment
                    </button>
                </div>
            </div>
        </div>

        <div class="row mb-4">
            <div class="col-md-4">
                <div class="stat-card <?php echo $is_current_year_paid ? 'paid' : 'unpaid'; ?>">
                    <i class="fas fa-calendar-check fa-2x text-<?php echo $is_current_year_paid ? 'success' : 'danger'; ?>"></i>
                    <h3><?php echo $current_year; ?></h3>
                    <p class="mb-0 text-muted">
                        <?php if($is_current_year_paid): ?>
                        <span class="text-success"><i class="fas fa-check mr-1"></i>Paid</span>
                        <?php else: ?>
                        <span class="text-danger"><i class="fas fa-times mr-1"></i>Unpaid</span>
                        <?php endif; ?>
                    </p>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stat-card">
                    <i class="fas fa-money-bill fa-2x text-primary"></i>
                    <h3>TZS <?php echo number_format($yearly_fee); ?></h3>
                    <p class="mb-0 text-muted">Yearly Fee</p>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stat-card">
                    <i class="fas fa-history fa-2x text-info"></i>
                    <h3><?php echo count($paid_years); ?></h3>
                    <p class="mb-0 text-muted">Years Paid</p>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-lg-8">
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-list mr-2"></i>Payment History
                    </div>
                    <div class="card-body">
                        <?php if(count($payments_arr) == 0): ?>
                        <div class="text-center py-4">
                            <i class="fas fa-receipt fa-3x text-muted mb-3"></i>
                            <p class="text-muted">No payments recorded yet</p>
                        </div>
                        <?php else: ?>
                        <div class="payment-timeline">
                            <?php foreach($payments_arr as $payment): ?>
                            <div class="payment-item <?php echo $payment['status']; ?>">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <h6 class="mb-1">
                                            <strong>Year <?php echo $payment['payment_year']; ?></strong>
                                            <span class="badge badge-<?php
                                                echo $payment['status'] == 'confirmed' ? 'success' :
                                                    ($payment['status'] == 'pending' ? 'warning' : 'danger');
                                            ?> ml-2"><?php echo ucfirst($payment['status']); ?></span>
                                        </h6>
                                        <p class="mb-1">
                                            <strong>Amount:</strong> TZS <?php echo number_format($payment['amount'], 2); ?>
                                        </p>
                                        <p class="mb-1 text-muted">
                                            <small>
                                                <i class="fas fa-calendar mr-1"></i><?php echo date('d M Y', strtotime($payment['payment_date'])); ?>
                                                | <i class="fas fa-credit-card mr-1"></i><?php echo ucfirst(str_replace('_', ' ', $payment['payment_method'])); ?>
                                                <?php if($payment['reference_number']): ?>
                                                | Ref: <?php echo htmlspecialchars($payment['reference_number']); ?>
                                                <?php endif; ?>
                                            </small>
                                        </p>
                                        <p class="mb-0 text-muted">
                                            <small>
                                                Recorded by: <?php echo htmlspecialchars($payment['recorded_by_name']); ?>
                                                <?php if($payment['confirmed_by_name']): ?>
                                                | Confirmed by: <?php echo htmlspecialchars($payment['confirmed_by_name']); ?>
                                                <?php endif; ?>
                                            </small>
                                        </p>
                                        <?php if($payment['notes']): ?>
                                        <p class="mb-0 mt-1"><small><i class="fas fa-sticky-note mr-1"></i><?php echo htmlspecialchars($payment['notes']); ?></small></p>
                                        <?php endif; ?>
                                    </div>
                                    <div>
                                        <?php if($payment['status'] == 'pending' && $user_role == 'admin'): ?>
                                        <form method="POST" class="d-inline">
                                            <input type="hidden" name="action" value="confirm_payment">
                                            <input type="hidden" name="payment_id" value="<?php echo $payment['id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-success" title="Confirm">
                                                <i class="fas fa-check"></i>
                                            </button>
                                        </form>
                                        <?php endif; ?>
                                        <?php if($payment['status'] != 'cancelled'): ?>
                                        <form method="POST" class="d-inline" onsubmit="return confirm('Cancel this payment?')">
                                            <input type="hidden" name="action" value="cancel_payment">
                                            <input type="hidden" name="payment_id" value="<?php echo $payment['id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-outline-danger" title="Cancel">
                                                <i class="fas fa-times"></i>
                                            </button>
                                        </form>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <div class="col-lg-4">
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-user mr-2"></i>Client Info
                    </div>
                    <div class="card-body">
                        <p><strong>Name:</strong> <?php echo htmlspecialchars($client['full_name']); ?></p>
                        <p><strong>Phone:</strong> <?php echo htmlspecialchars($client['phone']); ?></p>
                        <p><strong>Email:</strong> <?php echo htmlspecialchars($client['email']) ?: '-'; ?></p>
                        <p><strong>National ID:</strong> <?php echo htmlspecialchars($client['national_id']) ?: '-'; ?></p>
                        <p><strong>Broker:</strong> <?php echo htmlspecialchars($client['broker_name']); ?></p>
                        <p>
                            <strong>Status:</strong>
                            <span class="badge badge-<?php echo $client['access_status']; ?>">
                                <?php echo ucfirst($client['access_status']); ?>
                            </span>
                        </p>
                        <hr>
                        <a href="lands.php?client_id=<?php echo $client_id; ?>" class="btn btn-outline-primary btn-block">
                            <i class="fas fa-map mr-1"></i>View Client's Lands
                        </a>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-chart-bar mr-2"></i>Payment Years
                    </div>
                    <div class="card-body">
                        <?php
                        $start_year = 2020;
                        $end_year = $current_year + 1;
                        for($y = $end_year; $y >= $start_year; $y--):
                            $is_paid = in_array($y, $paid_years);
                        ?>
                        <div class="d-flex justify-content-between align-items-center py-2 border-bottom">
                            <span><?php echo $y; ?></span>
                            <?php if($is_paid): ?>
                            <span class="badge badge-success"><i class="fas fa-check mr-1"></i>Paid</span>
                            <?php else: ?>
                            <span class="badge badge-secondary">Unpaid</span>
                            <?php endif; ?>
                        </div>
                        <?php endfor; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Payment Modal -->
    <div class="modal fade" id="addPaymentModal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-plus mr-2"></i>Record Payment</h5>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>
                <form method="POST">
                    <input type="hidden" name="action" value="add_payment">
                    <div class="modal-body">
                        <div class="form-group">
                            <label>Amount (TZS) *</label>
                            <input type="number" name="amount" class="form-control" value="<?php echo $yearly_fee; ?>" required min="1" step="0.01">
                        </div>
                        <div class="form-group">
                            <label>Payment Year *</label>
                            <select name="payment_year" class="form-control" required>
                                <?php for($y = $current_year + 1; $y >= 2020; $y--): ?>
                                <option value="<?php echo $y; ?>" <?php echo $y == $current_year ? 'selected' : ''; ?>><?php echo $y; ?></option>
                                <?php endfor; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Payment Date *</label>
                            <input type="date" name="payment_date" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                        </div>
                        <div class="form-group">
                            <label>Payment Method</label>
                            <select name="payment_method" class="form-control">
                                <option value="cash">Cash</option>
                                <option value="bank_transfer">Bank Transfer</option>
                                <option value="mobile_money">Mobile Money (M-Pesa, Tigo Pesa, etc.)</option>
                                <option value="other">Other</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Reference Number</label>
                            <input type="text" name="reference_number" class="form-control" placeholder="Transaction ID, receipt number, etc.">
                        </div>
                        <div class="form-group">
                            <label>Receipt Number</label>
                            <input type="text" name="receipt_number" class="form-control">
                        </div>
                        <div class="form-group">
                            <label>Notes</label>
                            <textarea name="notes" class="form-control" rows="2"></textarea>
                        </div>
                        <?php if($user_role != 'admin'): ?>
                        <div class="alert alert-info mb-0">
                            <small><i class="fas fa-info-circle mr-1"></i>Payment will be marked as pending until confirmed by an administrator.</small>
                        </div>
                        <?php endif; ?>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Record Payment</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="assets/vendor/jquery/jquery.min.js"></script>
    <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        function toggleSidebar() {
            document.getElementById('sidebar').classList.toggle('active');
        }
    </script>
</body>
</html>
