<?php
/**
 * Payment Schedule Management
 * LandSales Pro - View and manage all payment schedules
 */
define('APP_RUNNING', true);
require_once '../../db_connect.php';
require_once '../../includes/auth.php';
require_once '../../includes/subscription.php';
require_once '../../includes/functions.php';

initSecureSession();
requireAuth();
requireSubscription();

$userId = $_SESSION['user_id'];

// Filters
$filterStatus = $_GET['status'] ?? 'all';
$filterProject = $_GET['project'] ?? '';
$filterSale = $_GET['sale_id'] ?? '';

// Get projects for filter
$projects = db_fetch_all("SELECT id, name FROM projects WHERE user_id = ? ORDER BY name", 'i', [$userId]);

// Build query
$whereClause = "WHERE s.user_id = ? AND s.status = 'active'";
$params = [$userId];
$types = 'i';

if ($filterStatus === 'pending') {
    $whereClause .= " AND ps.status = 'pending'";
} elseif ($filterStatus === 'overdue') {
    $whereClause .= " AND ps.status IN ('pending', 'overdue') AND ps.due_date < CURDATE()";
} elseif ($filterStatus === 'paid') {
    $whereClause .= " AND ps.status = 'paid'";
}

if ($filterProject) {
    $whereClause .= " AND pr.id = ?";
    $params[] = $filterProject;
    $types .= 'i';
}

if ($filterSale) {
    $whereClause .= " AND s.id = ?";
    $params[] = $filterSale;
    $types .= 'i';
}

// Get schedules
$schedules = db_fetch_all("SELECT ps.*, s.sale_number, s.total_price,
    b.id as buyer_id, b.full_name as buyer_name, b.phone as buyer_phone,
    p.plot_number, pr.id as project_id, pr.name as project_name,
    CASE
        WHEN ps.status = 'paid' THEN 0
        WHEN ps.due_date < CURDATE() THEN DATEDIFF(CURDATE(), ps.due_date)
        ELSE -DATEDIFF(ps.due_date, CURDATE())
    END as days_diff
    FROM payment_schedule ps
    JOIN sales s ON ps.sale_id = s.id
    JOIN buyers b ON s.buyer_id = b.id
    JOIN plots p ON s.plot_id = p.id
    JOIN projects pr ON p.project_id = pr.id
    {$whereClause}
    ORDER BY
        CASE WHEN ps.status = 'paid' THEN 1 ELSE 0 END,
        ps.due_date ASC,
        s.sale_number ASC,
        ps.installment_number ASC", $types, $params);

// Stats
$totalSchedules = count($schedules);
$pendingCount = 0;
$overdueCount = 0;
$paidCount = 0;
$totalPending = 0;
$totalOverdue = 0;
$totalPaid = 0;

foreach ($schedules as $s) {
    if ($s['status'] === 'paid') {
        $paidCount++;
        $totalPaid += $s['amount'];
    } elseif ($s['days_diff'] > 0) {
        $overdueCount++;
        $totalOverdue += $s['amount'];
    } else {
        $pendingCount++;
        $totalPending += $s['amount'];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Schedule - <?php echo APP_NAME; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/font-awesome/css/all.min.css">
</head>
<body>
    <?php include '../includes/sidebar.php'; ?>

    <div class="main-content">
        <?php
        $pageTitle = 'Payment Schedule';
        $headerActions = '<a href="index.php" class="btn btn-outline"><i class="fas fa-arrow-left"></i> Back</a>';
        include '../includes/header.php';
        ?>

        <div class="content-wrapper">
            <!-- Stats -->
            <div class="stats-row">
                <a href="?status=overdue" class="stat-mini danger <?php echo $filterStatus === 'overdue' ? 'active' : ''; ?>">
                    <i class="fas fa-exclamation-triangle"></i>
                    <div>
                        <div class="stat-value"><?php echo $overdueCount; ?></div>
                        <div class="stat-label">Overdue</div>
                    </div>
                    <div class="stat-amount">TZS <?php echo formatMoney($totalOverdue); ?></div>
                </a>
                <a href="?status=pending" class="stat-mini warning <?php echo $filterStatus === 'pending' ? 'active' : ''; ?>">
                    <i class="fas fa-clock"></i>
                    <div>
                        <div class="stat-value"><?php echo $pendingCount; ?></div>
                        <div class="stat-label">Pending</div>
                    </div>
                    <div class="stat-amount">TZS <?php echo formatMoney($totalPending); ?></div>
                </a>
                <a href="?status=paid" class="stat-mini success <?php echo $filterStatus === 'paid' ? 'active' : ''; ?>">
                    <i class="fas fa-check-circle"></i>
                    <div>
                        <div class="stat-value"><?php echo $paidCount; ?></div>
                        <div class="stat-label">Paid</div>
                    </div>
                    <div class="stat-amount">TZS <?php echo formatMoney($totalPaid); ?></div>
                </a>
                <a href="?status=all" class="stat-mini info <?php echo $filterStatus === 'all' ? 'active' : ''; ?>">
                    <i class="fas fa-list"></i>
                    <div>
                        <div class="stat-value"><?php echo $totalSchedules; ?></div>
                        <div class="stat-label">Total</div>
                    </div>
                </a>
            </div>

            <!-- Filters -->
            <div class="filters-card">
                <form method="GET" class="filters-form">
                    <input type="hidden" name="status" value="<?php echo htmlspecialchars($filterStatus); ?>">
                    <div class="filter-group">
                        <label>Project</label>
                        <select name="project" onchange="this.form.submit()">
                            <option value="">All Projects</option>
                            <?php foreach ($projects as $proj): ?>
                            <option value="<?php echo $proj['id']; ?>" <?php echo $filterProject == $proj['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($proj['name']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php if ($filterProject || $filterSale): ?>
                    <a href="?status=<?php echo $filterStatus; ?>" class="btn btn-outline btn-sm">
                        <i class="fas fa-times"></i> Clear Filters
                    </a>
                    <?php endif; ?>
                </form>
            </div>

            <!-- Schedule Table -->
            <div class="card">
                <div class="card-header">
                    <h3>
                        <i class="fas fa-calendar-alt"></i>
                        <?php
                        if ($filterStatus === 'overdue') echo 'Overdue Payments';
                        elseif ($filterStatus === 'pending') echo 'Pending Payments';
                        elseif ($filterStatus === 'paid') echo 'Paid Payments';
                        else echo 'All Payment Schedules';
                        ?>
                    </h3>
                    <span class="badge"><?php echo count($schedules); ?> items</span>
                </div>
                <?php if (empty($schedules)): ?>
                <div class="empty-state">
                    <i class="fas fa-calendar-check"></i>
                    <h3>No Payment Schedules</h3>
                    <p>No payment schedules found with the selected filters.</p>
                </div>
                <?php else: ?>
                <div class="table-responsive">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Sale / Buyer</th>
                                <th>Plot</th>
                                <th>Installment</th>
                                <th>Due Date</th>
                                <th>Amount</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($schedules as $item): ?>
                            <tr class="<?php echo $item['status'] === 'paid' ? 'paid-row' : ''; ?>">
                                <td>
                                    <div class="sale-info">
                                        <div class="sale-number"><?php echo htmlspecialchars($item['sale_number']); ?></div>
                                        <div class="buyer-name"><?php echo htmlspecialchars($item['buyer_name']); ?></div>
                                        <div class="buyer-phone">
                                            <a href="tel:<?php echo $item['buyer_phone']; ?>"><?php echo $item['buyer_phone']; ?></a>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <div class="plot-info">
                                        <div class="plot-number">Plot <?php echo $item['plot_number']; ?></div>
                                        <div class="project-name"><?php echo htmlspecialchars($item['project_name']); ?></div>
                                    </div>
                                </td>
                                <td>
                                    <span class="installment-badge">#<?php echo $item['installment_number']; ?></span>
                                </td>
                                <td>
                                    <div class="due-date">
                                        <?php echo date('M j, Y', strtotime($item['due_date'])); ?>
                                        <?php if ($item['status'] !== 'paid'): ?>
                                        <div class="days-label <?php echo $item['days_diff'] > 0 ? 'overdue' : ($item['days_diff'] == 0 ? 'today' : 'upcoming'); ?>">
                                            <?php
                                            if ($item['days_diff'] > 0) {
                                                echo $item['days_diff'] . ' days overdue';
                                            } elseif ($item['days_diff'] == 0) {
                                                echo 'Due today';
                                            } else {
                                                echo 'In ' . abs($item['days_diff']) . ' days';
                                            }
                                            ?>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </td>
                                <td class="<?php echo $item['status'] !== 'paid' && $item['days_diff'] > 0 ? 'text-danger' : ''; ?>">
                                    TZS <?php echo number_format($item['amount']); ?>
                                </td>
                                <td>
                                    <?php if ($item['status'] === 'paid'): ?>
                                    <span class="status-badge paid">
                                        <i class="fas fa-check"></i> Paid
                                        <?php if ($item['paid_date']): ?>
                                        <small><?php echo date('M j', strtotime($item['paid_date'])); ?></small>
                                        <?php endif; ?>
                                    </span>
                                    <?php elseif ($item['days_diff'] > 0): ?>
                                    <span class="status-badge overdue">
                                        <i class="fas fa-exclamation-triangle"></i> Overdue
                                    </span>
                                    <?php elseif ($item['days_diff'] == 0): ?>
                                    <span class="status-badge today">
                                        <i class="fas fa-bell"></i> Due Today
                                    </span>
                                    <?php else: ?>
                                    <span class="status-badge pending">
                                        <i class="fas fa-clock"></i> Pending
                                    </span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div class="action-buttons">
                                        <?php if ($item['status'] !== 'paid'): ?>
                                        <a href="create.php?sale_id=<?php echo $item['sale_id']; ?>" class="btn btn-primary btn-sm" title="Record Payment">
                                            <i class="fas fa-money-bill-wave"></i>
                                        </a>
                                        <a href="https://wa.me/<?php echo preg_replace('/[^0-9]/', '', $item['buyer_phone']); ?>?text=<?php echo urlencode("Hello {$item['buyer_name']}, this is a reminder about your payment of TZS " . number_format($item['amount']) . " for Plot {$item['plot_number']} (Installment #{$item['installment_number']})."); ?>" target="_blank" class="btn btn-outline btn-sm" title="WhatsApp">
                                            <i class="fab fa-whatsapp"></i>
                                        </a>
                                        <?php endif; ?>
                                        <a href="../sales/view.php?id=<?php echo $item['sale_id']; ?>" class="btn btn-outline btn-sm" title="View Sale">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <style>
        body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; margin: 0; background: #f1f5f9; }
        .btn { padding: 0.625rem 1.25rem; border-radius: 8px; font-weight: 500; text-decoration: none; display: inline-flex; align-items: center; gap: 0.5rem; transition: all 0.2s; border: none; cursor: pointer; font-size: 0.875rem; }
        .btn-sm { padding: 0.5rem 0.75rem; font-size: 0.8rem; }
        .btn-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .btn-outline { border: 1px solid #e2e8f0; background: white; color: #64748b; }

        .stats-row { display: flex; gap: 1rem; margin-bottom: 1.5rem; flex-wrap: wrap; }
        .stat-mini { flex: 1; min-width: 180px; padding: 1rem; background: white; border-radius: 10px; display: flex; align-items: center; gap: 0.75rem; box-shadow: 0 2px 8px rgba(0,0,0,0.05); text-decoration: none; color: inherit; transition: all 0.2s; }
        .stat-mini:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
        .stat-mini.active { box-shadow: 0 0 0 2px #667eea; }
        .stat-mini i { width: 40px; height: 40px; background: #f1f5f9; border-radius: 10px; display: flex; align-items: center; justify-content: center; color: #64748b; flex-shrink: 0; }
        .stat-mini.danger { border-left: 3px solid #ef4444; }
        .stat-mini.danger i { background: #fee2e2; color: #dc2626; }
        .stat-mini.warning { border-left: 3px solid #f59e0b; }
        .stat-mini.warning i { background: #fef3c7; color: #d97706; }
        .stat-mini.success { border-left: 3px solid #22c55e; }
        .stat-mini.success i { background: #dcfce7; color: #16a34a; }
        .stat-mini.info { border-left: 3px solid #3b82f6; }
        .stat-mini.info i { background: #dbeafe; color: #2563eb; }
        .stat-mini .stat-value { font-size: 1.5rem; font-weight: 700; color: #1e293b; }
        .stat-mini .stat-label { font-size: 0.75rem; color: #64748b; }
        .stat-mini .stat-amount { margin-left: auto; font-size: 0.8rem; font-weight: 600; color: #64748b; }

        .filters-card { background: white; border-radius: 10px; padding: 1rem; margin-bottom: 1.5rem; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
        .filters-form { display: flex; gap: 1rem; align-items: flex-end; flex-wrap: wrap; }
        .filter-group { display: flex; flex-direction: column; gap: 0.35rem; }
        .filter-group label { font-size: 0.75rem; color: #64748b; font-weight: 500; }
        .filter-group select { padding: 0.5rem 0.75rem; border: 1px solid #e2e8f0; border-radius: 6px; font-size: 0.85rem; min-width: 180px; }

        .card { background: white; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); overflow: hidden; margin-bottom: 1.5rem; }
        .card-header { padding: 1rem 1.25rem; border-bottom: 1px solid #f1f5f9; background: #f8fafc; display: flex; justify-content: space-between; align-items: center; }
        .card-header h3 { margin: 0; font-size: 0.95rem; font-weight: 600; color: #1e293b; display: flex; align-items: center; gap: 0.5rem; }
        .card-header h3 i { color: #667eea; }

        .badge { padding: 0.25rem 0.75rem; border-radius: 20px; font-size: 0.7rem; font-weight: 600; background: #f1f5f9; color: #64748b; }

        .table-responsive { overflow-x: auto; }
        .data-table { width: 100%; border-collapse: collapse; }
        .data-table th, .data-table td { padding: 0.875rem 1rem; text-align: left; border-bottom: 1px solid #f1f5f9; }
        .data-table th { background: #f8fafc; font-weight: 600; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.5px; color: #64748b; }
        .data-table tbody tr:hover { background: #f8fafc; }
        .data-table tr.paid-row { opacity: 0.6; background: #f8fafc; }

        .sale-number { font-weight: 600; color: #667eea; font-size: 0.85rem; }
        .buyer-name { font-weight: 500; color: #1e293b; }
        .buyer-phone { font-size: 0.8rem; }
        .buyer-phone a { color: #667eea; text-decoration: none; }
        .plot-number { font-weight: 500; color: #1e293b; }
        .project-name { font-size: 0.8rem; color: #64748b; }

        .installment-badge { background: #f1f5f9; padding: 0.25rem 0.5rem; border-radius: 4px; font-size: 0.8rem; font-weight: 600; color: #64748b; }

        .due-date { font-size: 0.9rem; }
        .days-label { font-size: 0.7rem; margin-top: 0.25rem; font-weight: 500; }
        .days-label.overdue { color: #dc2626; }
        .days-label.today { color: #7c3aed; }
        .days-label.upcoming { color: #64748b; }

        .status-badge { padding: 0.35rem 0.6rem; border-radius: 6px; font-size: 0.75rem; font-weight: 500; display: inline-flex; align-items: center; gap: 0.35rem; }
        .status-badge.paid { background: #dcfce7; color: #16a34a; }
        .status-badge.overdue { background: #fee2e2; color: #dc2626; }
        .status-badge.today { background: #ede9fe; color: #7c3aed; }
        .status-badge.pending { background: #fef3c7; color: #d97706; }
        .status-badge small { font-size: 0.65rem; opacity: 0.8; }

        .text-danger { color: #dc2626; font-weight: 600; }
        .action-buttons { display: flex; gap: 0.5rem; }

        .empty-state { text-align: center; padding: 3rem; color: #64748b; }
        .empty-state i { font-size: 3rem; color: #94a3b8; margin-bottom: 1rem; }
        .empty-state h3 { margin: 0 0 0.5rem; color: #1e293b; }
        .empty-state p { margin: 0; }

        @media (max-width: 768px) {
            .stats-row { flex-direction: column; }
            .action-buttons { flex-direction: column; }
            .filters-form { flex-direction: column; align-items: stretch; }
        }
    </style>
</body>
</html>
