<?php
/**
 * Payment Reminders
 * LandSales Pro - View overdue and upcoming payments with follow-up tracking
 */
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'];
$today = date('Y-m-d');

// Get overdue payments (from payment schedule) with followup status
$overdue = 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.name as project_name,
    DATEDIFF(CURDATE(), ps.due_date) as days_overdue,
    pf.status as followup_status, pf.notes as followup_notes,
    pf.promised_date, pf.called_at
    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
    LEFT JOIN payment_followups pf ON ps.id = pf.payment_schedule_id AND pf.followup_date = ?
    WHERE s.user_id = ? AND s.status = 'active' AND ps.status IN ('pending', 'overdue') AND ps.due_date < CURDATE()
    ORDER BY ps.due_date ASC", 'si', [$today, $userId]);

// Get today's payments with followup status
$todayPayments = 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.name as project_name,
    pf.status as followup_status, pf.notes as followup_notes,
    pf.promised_date, pf.called_at
    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
    LEFT JOIN payment_followups pf ON ps.id = pf.payment_schedule_id AND pf.followup_date = ?
    WHERE s.user_id = ? AND s.status = 'active' AND ps.status IN ('pending', 'overdue')
    AND ps.due_date = CURDATE()
    ORDER BY b.full_name ASC", 'si', [$today, $userId]);

// Get upcoming payments (next 30 days)
$upcoming = 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.name as project_name,
    DATEDIFF(ps.due_date, CURDATE()) as days_until
    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
    WHERE s.user_id = ? AND s.status = 'active' AND ps.status = 'pending'
    AND ps.due_date > CURDATE() AND ps.due_date <= DATE_ADD(CURDATE(), INTERVAL 30 DAY)
    ORDER BY ps.due_date ASC", 'i', [$userId]);

// Get sales with outstanding balances (no schedule)
$outstanding = db_fetch_all("SELECT s.*, b.full_name as buyer_name, b.phone as buyer_phone,
    p.plot_number, pr.name as project_name,
    (s.total_price - COALESCE((SELECT SUM(amount) FROM payments WHERE sale_id = s.id AND status = 'confirmed'), 0)) as balance,
    DATEDIFF(CURDATE(), s.sale_date) as days_since_sale
    FROM sales s
    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
    WHERE s.user_id = ? AND s.status = 'active'
    AND NOT EXISTS (SELECT 1 FROM payment_schedule WHERE sale_id = s.id)
    HAVING balance > 0
    ORDER BY s.sale_date ASC", 'i', [$userId]);

// Stats
$totalOverdue = array_sum(array_column($overdue, 'amount'));
$totalToday = array_sum(array_column($todayPayments, 'amount'));
$totalUpcoming = array_sum(array_column($upcoming, 'amount'));
$totalOutstanding = array_sum(array_column($outstanding, 'balance'));

// Count pending followups for today
$pendingTodayCount = 0;
foreach ($todayPayments as $p) {
    if (empty($p['followup_status']) || $p['followup_status'] === 'pending') {
        $pendingTodayCount++;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Reminders - <?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 Reminders';
        $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">
                <div class="stat-mini danger">
                    <i class="fas fa-exclamation-triangle"></i>
                    <div>
                        <div class="stat-value"><?php echo count($overdue); ?></div>
                        <div class="stat-label">Overdue</div>
                    </div>
                    <div class="stat-amount">TZS <?php echo formatMoney($totalOverdue); ?></div>
                </div>
                <div class="stat-mini today">
                    <i class="fas fa-bell"></i>
                    <div>
                        <div class="stat-value"><?php echo count($todayPayments); ?></div>
                        <div class="stat-label">Due Today</div>
                    </div>
                    <div class="stat-amount">TZS <?php echo formatMoney($totalToday); ?></div>
                </div>
                <div class="stat-mini warning">
                    <i class="fas fa-clock"></i>
                    <div>
                        <div class="stat-value"><?php echo count($upcoming); ?></div>
                        <div class="stat-label">Due Soon</div>
                    </div>
                    <div class="stat-amount">TZS <?php echo formatMoney($totalUpcoming); ?></div>
                </div>
                <div class="stat-mini info">
                    <i class="fas fa-file-invoice-dollar"></i>
                    <div>
                        <div class="stat-value"><?php echo count($outstanding); ?></div>
                        <div class="stat-label">Outstanding</div>
                    </div>
                    <div class="stat-amount">TZS <?php echo formatMoney($totalOutstanding); ?></div>
                </div>
            </div>

            <!-- Due Today -->
            <?php if (!empty($todayPayments)): ?>
            <div class="card today-card">
                <div class="card-header">
                    <h3><i class="fas fa-bell"></i> Due Today (<?php echo date('M j, Y'); ?>)</h3>
                    <span class="badge badge-today"><?php echo $pendingTodayCount; ?> pending follow-up</span>
                </div>
                <div class="table-responsive">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Buyer</th>
                                <th>Plot</th>
                                <th>Installment</th>
                                <th>Amount</th>
                                <th>Follow-up Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($todayPayments as $item): ?>
                            <tr class="<?php echo (!empty($item['followup_status']) && $item['followup_status'] !== 'pending') ? 'handled' : ''; ?>">
                                <td>
                                    <div class="buyer-info">
                                        <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>Installment #<?php echo $item['installment_number']; ?></td>
                                <td class="text-primary">TZS <?php echo number_format($item['amount']); ?></td>
                                <td>
                                    <?php if (empty($item['followup_status']) || $item['followup_status'] === 'pending'): ?>
                                    <span class="status-badge pending"><i class="fas fa-clock"></i> Pending</span>
                                    <?php else: ?>
                                    <?php
                                    $statusLabels = [
                                        'called' => ['icon' => 'fa-phone', 'label' => 'Called', 'class' => 'called'],
                                        'no_answer' => ['icon' => 'fa-phone-slash', 'label' => 'No Answer', 'class' => 'no-answer'],
                                        'promised_today' => ['icon' => 'fa-handshake', 'label' => 'Promised Today', 'class' => 'promised'],
                                        'rescheduled' => ['icon' => 'fa-calendar-alt', 'label' => 'Promised: ' . ($item['promised_date'] ? date('M j', strtotime($item['promised_date'])) : ''), 'class' => 'rescheduled'],
                                        'paid' => ['icon' => 'fa-check', 'label' => 'Marked Paid', 'class' => 'paid']
                                    ];
                                    $status = $statusLabels[$item['followup_status']] ?? ['icon' => 'fa-clock', 'label' => ucfirst($item['followup_status']), 'class' => ''];
                                    ?>
                                    <span class="status-badge <?php echo $status['class']; ?>">
                                        <i class="fas <?php echo $status['icon']; ?>"></i> <?php echo $status['label']; ?>
                                        <?php if ($item['called_at']): ?>
                                        <small>@ <?php echo date('g:i A', strtotime($item['called_at'])); ?></small>
                                        <?php endif; ?>
                                    </span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div class="action-buttons">
                                        <?php if (empty($item['followup_status']) || $item['followup_status'] === 'pending'): ?>
                                        <button class="btn btn-promised btn-sm" onclick="showPromised(<?php echo $item['id']; ?>)">
                                            <i class="fas fa-handshake"></i> Promised
                                        </button>
                                        <button class="btn btn-no-answer btn-sm" onclick="markFollowup(<?php echo $item['id']; ?>, 'no_answer')">
                                            <i class="fas fa-phone-slash"></i>
                                        </button>
                                        <button class="btn btn-paid btn-sm" onclick="markFollowup(<?php echo $item['id']; ?>, 'paid')">
                                            <i class="fas fa-check"></i>
                                        </button>
                                        <?php endif; ?>
                                        <a href="create.php?sale_id=<?php echo $item['sale_id']; ?>" class="btn btn-primary btn-sm">
                                            <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']} due today."); ?>" target="_blank" class="btn btn-outline btn-sm">
                                            <i class="fab fa-whatsapp"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <?php endif; ?>

            <!-- Overdue Payments -->
            <?php if (!empty($overdue)): ?>
            <div class="card danger-card">
                <div class="card-header">
                    <h3><i class="fas fa-exclamation-triangle"></i> Overdue Payments</h3>
                    <span class="badge badge-danger"><?php echo count($overdue); ?> overdue</span>
                </div>
                <div class="table-responsive">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Buyer</th>
                                <th>Plot</th>
                                <th>Due Date</th>
                                <th>Days Overdue</th>
                                <th>Amount</th>
                                <th>Follow-up</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($overdue as $item): ?>
                            <tr class="<?php echo (!empty($item['followup_status']) && $item['followup_status'] !== 'pending') ? 'handled' : ''; ?>">
                                <td>
                                    <div class="buyer-info">
                                        <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><?php echo date('M j, Y', strtotime($item['due_date'])); ?></td>
                                <td>
                                    <span class="overdue-badge"><?php echo $item['days_overdue']; ?> days</span>
                                </td>
                                <td class="text-danger">TZS <?php echo number_format($item['amount']); ?></td>
                                <td>
                                    <?php if (empty($item['followup_status']) || $item['followup_status'] === 'pending'): ?>
                                    <div class="followup-actions-mini">
                                        <button class="btn-mini promised" onclick="showPromised(<?php echo $item['id']; ?>)" title="Promised to pay">
                                            <i class="fas fa-handshake"></i>
                                        </button>
                                        <button class="btn-mini no-answer" onclick="markFollowup(<?php echo $item['id']; ?>, 'no_answer')" title="No answer">
                                            <i class="fas fa-phone-slash"></i>
                                        </button>
                                        <button class="btn-mini paid" onclick="markFollowup(<?php echo $item['id']; ?>, 'paid')" title="Paid">
                                            <i class="fas fa-check"></i>
                                        </button>
                                    </div>
                                    <?php else: ?>
                                    <?php
                                    $statusLabels = [
                                        'called' => ['icon' => 'fa-phone', 'label' => 'Called', 'class' => 'called'],
                                        'no_answer' => ['icon' => 'fa-phone-slash', 'label' => 'No Answer', 'class' => 'no-answer'],
                                        'promised_today' => ['icon' => 'fa-handshake', 'label' => 'Promised', 'class' => 'promised'],
                                        'rescheduled' => ['icon' => 'fa-calendar-alt', 'label' => $item['promised_date'] ? date('M j', strtotime($item['promised_date'])) : 'Rescheduled', 'class' => 'rescheduled'],
                                        'paid' => ['icon' => 'fa-check', 'label' => 'Paid', 'class' => 'paid']
                                    ];
                                    $status = $statusLabels[$item['followup_status']] ?? ['icon' => 'fa-clock', 'label' => ucfirst($item['followup_status']), 'class' => ''];
                                    ?>
                                    <span class="status-badge <?php echo $status['class']; ?>">
                                        <i class="fas <?php echo $status['icon']; ?>"></i> <?php echo $status['label']; ?>
                                    </span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div class="action-buttons">
                                        <a href="create.php?sale_id=<?php echo $item['sale_id']; ?>" class="btn btn-primary btn-sm">
                                            <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 overdue payment of TZS " . number_format($item['amount']) . " for Plot {$item['plot_number']} which was due on " . date('M j, Y', strtotime($item['due_date'])) . ". Please make the payment at your earliest convenience."); ?>" target="_blank" class="btn btn-outline btn-sm">
                                            <i class="fab fa-whatsapp"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <?php endif; ?>

            <!-- Upcoming Payments -->
            <?php if (!empty($upcoming)): ?>
            <div class="card warning-card">
                <div class="card-header">
                    <h3><i class="fas fa-clock"></i> Upcoming Payments (Next 30 Days)</h3>
                    <span class="badge badge-warning"><?php echo count($upcoming); ?> due soon</span>
                </div>
                <div class="table-responsive">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Buyer</th>
                                <th>Plot</th>
                                <th>Due Date</th>
                                <th>Days Until</th>
                                <th>Amount</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($upcoming as $item): ?>
                            <tr>
                                <td>
                                    <div class="buyer-info">
                                        <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><?php echo date('M j, Y', strtotime($item['due_date'])); ?></td>
                                <td>
                                    <span class="upcoming-badge <?php echo $item['days_until'] <= 7 ? 'soon' : ''; ?>">
                                        <?php echo $item['days_until'] == 0 ? 'Today' : $item['days_until'] . ' days'; ?>
                                    </span>
                                </td>
                                <td>TZS <?php echo number_format($item['amount']); ?></td>
                                <td>
                                    <div class="action-buttons">
                                        <a href="create.php?sale_id=<?php echo $item['sale_id']; ?>" class="btn btn-outline btn-sm">
                                            <i class="fas fa-money-bill-wave"></i> Record
                                        </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 upcoming payment of TZS " . number_format($item['amount']) . " for Plot {$item['plot_number']} due on " . date('M j, Y', strtotime($item['due_date'])) . "."); ?>" target="_blank" class="btn btn-outline btn-sm">
                                            <i class="fab fa-whatsapp"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <?php endif; ?>

            <!-- Outstanding Balances -->
            <?php if (!empty($outstanding)): ?>
            <div class="card">
                <div class="card-header">
                    <h3><i class="fas fa-file-invoice-dollar"></i> Outstanding Balances (No Schedule)</h3>
                    <span class="badge"><?php echo count($outstanding); ?> sales</span>
                </div>
                <div class="table-responsive">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Buyer</th>
                                <th>Plot</th>
                                <th>Sale Date</th>
                                <th>Total Price</th>
                                <th>Balance</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($outstanding as $item): ?>
                            <tr>
                                <td>
                                    <div class="buyer-info">
                                        <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>
                                    <?php echo date('M j, Y', strtotime($item['sale_date'])); ?>
                                    <br><small class="text-muted"><?php echo $item['days_since_sale']; ?> days ago</small>
                                </td>
                                <td>TZS <?php echo number_format($item['total_price']); ?></td>
                                <td class="text-warning">TZS <?php echo number_format($item['balance']); ?></td>
                                <td>
                                    <div class="action-buttons">
                                        <a href="create.php?sale_id=<?php echo $item['id']; ?>" class="btn btn-primary btn-sm">
                                            <i class="fas fa-money-bill-wave"></i> Record
                                        </a>
                                        <a href="../sales/view.php?id=<?php echo $item['id']; ?>" class="btn btn-outline btn-sm">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <?php endif; ?>

            <?php if (empty($overdue) && empty($upcoming) && empty($outstanding)): ?>
            <div class="card">
                <div class="empty-state">
                    <i class="fas fa-check-circle"></i>
                    <h3>All Caught Up!</h3>
                    <p>No overdue or upcoming payments at the moment.</p>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <style>
        body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; margin: 0; background: #f1f5f9; }
        .header-actions { display: flex; gap: 0.75rem; }
        .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: 200px; 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); }
        .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.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.85rem; font-weight: 600; color: #64748b; }

        .card { background: white; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); overflow: hidden; margin-bottom: 1.5rem; }
        .danger-card { border-top: 3px solid #ef4444; }
        .warning-card { border-top: 3px solid #f59e0b; }
        .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; }
        .danger-card .card-header h3 i { color: #ef4444; }
        .warning-card .card-header h3 i { color: #f59e0b; }

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

        .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; }

        .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; }
        .text-muted { color: #94a3b8; }

        .overdue-badge { background: #fee2e2; color: #dc2626; padding: 0.25rem 0.5rem; border-radius: 4px; font-size: 0.75rem; font-weight: 600; }
        .upcoming-badge { background: #fef3c7; color: #d97706; padding: 0.25rem 0.5rem; border-radius: 4px; font-size: 0.75rem; font-weight: 600; }
        .upcoming-badge.soon { background: #fee2e2; color: #dc2626; }

        .text-danger { color: #dc2626; font-weight: 600; }
        .text-warning { color: #d97706; 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: #22c55e; margin-bottom: 1rem; }
        .empty-state h3 { margin: 0 0 0.5rem; color: #1e293b; }
        .empty-state p { margin: 0; }

        /* Today card */
        .stat-mini.today { border-left: 3px solid #7c3aed; }
        .stat-mini.today i { background: #ede9fe; color: #7c3aed; }
        .today-card { border-top: 3px solid #7c3aed; }
        .today-card .card-header h3 i { color: #7c3aed; }
        .badge-today { background: #ede9fe; color: #7c3aed; }

        /* Handled rows */
        tr.handled { opacity: 0.6; background: #f8fafc; }

        /* Status badges */
        .status-badge { padding: 0.35rem 0.5rem; border-radius: 6px; font-size: 0.75rem; font-weight: 500; display: inline-flex; align-items: center; gap: 0.35rem; white-space: nowrap; }
        .status-badge.pending { background: #f1f5f9; color: #64748b; }
        .status-badge.called { background: #dbeafe; color: #2563eb; }
        .status-badge.no-answer { background: #fef3c7; color: #d97706; }
        .status-badge.promised { background: #ede9fe; color: #7c3aed; }
        .status-badge.rescheduled { background: #f3e8ff; color: #9333ea; }
        .status-badge.paid { background: #dcfce7; color: #16a34a; }
        .status-badge small { font-size: 0.65rem; opacity: 0.8; }

        /* Mini followup buttons */
        .followup-actions-mini { display: flex; gap: 0.35rem; }
        .btn-mini { width: 28px; height: 28px; border-radius: 6px; border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 0.75rem; transition: all 0.2s; }
        .btn-mini.promised { background: #ede9fe; color: #7c3aed; }
        .btn-mini.promised:hover { background: #ddd6fe; }
        .btn-mini.no-answer { background: #fef3c7; color: #d97706; }
        .btn-mini.no-answer:hover { background: #fde68a; }
        .btn-mini.paid { background: #dcfce7; color: #16a34a; }
        .btn-mini.paid:hover { background: #bbf7d0; }

        /* Action buttons variants */
        .btn-promised { background: #ede9fe; color: #7c3aed; border: none; }
        .btn-promised:hover { background: #ddd6fe; }
        .btn-no-answer { background: #fef3c7; color: #d97706; border: none; }
        .btn-no-answer:hover { background: #fde68a; }
        .btn-paid { background: #dcfce7; color: #16a34a; border: none; }
        .btn-paid:hover { background: #bbf7d0; }

        .text-primary { color: #667eea; font-weight: 600; }

        @media (max-width: 768px) {
            .stats-row { flex-direction: column; }
            .action-buttons { flex-direction: column; }
            .followup-actions-mini { flex-wrap: wrap; }
        }
    </style>

    <script>
        // Followup functions for reminders page
        let currentScheduleId = null;

        function showPromised(scheduleId) {
            currentScheduleId = scheduleId;
            document.getElementById('promisedModal').classList.add('show');
            document.getElementById('promisedDate').value = '';
            document.getElementById('promisedNotes').value = '';
            document.getElementById('promisedDateGroup').style.display = 'none';
            document.querySelectorAll('input[name="promisedType"]').forEach(r => r.checked = false);

            const tomorrow = new Date();
            tomorrow.setDate(tomorrow.getDate() + 1);
            document.getElementById('promisedDate').min = tomorrow.toISOString().split('T')[0];
        }

        function closePromised() {
            document.getElementById('promisedModal').classList.remove('show');
            currentScheduleId = null;
        }

        function togglePromisedDate(show) {
            document.getElementById('promisedDateGroup').style.display = show ? 'block' : 'none';
        }

        function submitPromised() {
            const promisedType = document.querySelector('input[name="promisedType"]:checked')?.value;
            const notes = document.getElementById('promisedNotes').value;

            if (!promisedType) {
                alert('Please select when the buyer promised to pay');
                return;
            }

            if (promisedType === 'today') {
                markFollowup(currentScheduleId, 'promised_today', notes);
            } else {
                const date = document.getElementById('promisedDate').value;
                if (!date) {
                    alert('Please select the promised payment date');
                    return;
                }
                markFollowup(currentScheduleId, 'rescheduled', notes, date);
            }
            closePromised();
        }

        async function markFollowup(scheduleId, action, notes = '', promisedDate = null) {
            try {
                const response = await fetch('<?php echo SITE_URL; ?>/ajax/update-followup.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        schedule_id: scheduleId,
                        action: action,
                        notes: notes,
                        promised_date: promisedDate
                    })
                });

                const data = await response.json();

                if (data.success) {
                    location.reload();
                } else {
                    alert(data.error || 'Failed to update');
                }
            } catch (error) {
                console.error('Error:', error);
                alert('Failed to update followup');
            }
        }

        // Also support the global FollowupNotifications if available (from header)
        if (typeof FollowupNotifications !== 'undefined') {
            FollowupNotifications.togglePromisedDate = togglePromisedDate;
            FollowupNotifications.closePromised = closePromised;
            FollowupNotifications.submitPromised = submitPromised;
        }
    </script>
</body>
</html>
