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

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

$user_id = $_SESSION['user_id'];
$error = '';
$success = '';

// Handle settings update
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $yearly_fee = floatval($_POST['yearly_fee']);
    $premium_yearly_fee = floatval($_POST['premium_yearly_fee']);
    $max_images_per_land = intval($_POST['max_images_per_land']);
    $grace_period = intval($_POST['grace_period_days']);
    $due_month = intval($_POST['payment_due_month']);
    $due_day = intval($_POST['payment_due_day']);

    if($yearly_fee < 0) {
        $error = 'Yearly fee cannot be negative';
    } elseif($premium_yearly_fee < 0) {
        $error = 'Premium yearly fee cannot be negative';
    } elseif($premium_yearly_fee < $yearly_fee) {
        $error = 'Premium fee should be higher than or equal to basic fee';
    } elseif($max_images_per_land < 1 || $max_images_per_land > 20) {
        $error = 'Max images must be between 1 and 20';
    } elseif($grace_period < 0 || $grace_period > 365) {
        $error = 'Grace period must be between 0 and 365 days';
    } elseif($due_month < 1 || $due_month > 12) {
        $error = 'Invalid due month';
    } elseif($due_day < 1 || $due_day > 31) {
        $error = 'Invalid due day';
    } else {
        $updates = [
            'yearly_fee' => $yearly_fee,
            'premium_yearly_fee' => $premium_yearly_fee,
            'max_images_per_land' => $max_images_per_land,
            'grace_period_days' => $grace_period,
            'payment_due_month' => $due_month,
            'payment_due_day' => $due_day
        ];

        foreach($updates as $key => $value) {
            mysqli_query($conn, "INSERT INTO payment_settings (setting_key, setting_value)
                                 VALUES ('$key', '$value')
                                 ON DUPLICATE KEY UPDATE setting_value = '$value'");
        }
        $success = 'Payment settings updated successfully';
    }
}

// Get current 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'];
}

// Get payment statistics
$current_year = date('Y');
$stats = [];

// Total clients
$r = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as cnt FROM clients"));
$stats['total_clients'] = $r['cnt'];

// Paid this year
$r = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(DISTINCT client_id) as cnt FROM client_payments WHERE payment_year = $current_year AND status = 'confirmed'"));
$stats['paid_this_year'] = $r['cnt'];

// Pending payments
$r = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as cnt FROM client_payments WHERE status = 'pending'"));
$stats['pending_payments'] = $r['cnt'];

// Total collected this year
$r = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COALESCE(SUM(amount), 0) as total FROM client_payments WHERE payment_year = $current_year AND status = 'confirmed'"));
$stats['collected_this_year'] = $r['total'];

// Get all clients with payment status
$clients_result = mysqli_query($conn, "
    SELECT c.*, u.full_name as broker_name,
           (SELECT MAX(payment_year) FROM client_payments WHERE client_id = c.id AND status = 'confirmed') as last_paid_year,
           (SELECT SUM(amount) FROM client_payments WHERE client_id = c.id AND status = 'confirmed') as total_paid
    FROM clients c
    JOIN users u ON c.broker_id = u.id
    ORDER BY c.full_name
");

// Get pending payments
$pending_result = mysqli_query($conn, "
    SELECT cp.*, c.full_name as client_name, c.phone, u.full_name as broker_name, u2.full_name as recorded_by_name
    FROM client_payments cp
    JOIN clients c ON cp.client_id = c.id
    JOIN users u ON c.broker_id = u.id
    JOIN users u2 ON cp.recorded_by = u2.id
    WHERE cp.status = 'pending'
    ORDER BY cp.created_at DESC
");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Settings - Admin</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">
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="admin-main">
        <!-- Page Header -->
        <div class="page-header">
            <div class="page-header-content">
                <div class="page-title">
                    <h1><i class="fas fa-credit-card"></i> Payment Management</h1>
                    <p>Configure payment settings and manage client subscriptions</p>
                </div>
            </div>
        </div>

        <?php if($error): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <i class="fas fa-exclamation-circle mr-2"></i><?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">
            <i class="fas fa-check-circle mr-2"></i><?php echo $success; ?>
            <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
        <?php endif; ?>

        <!-- Stats Cards -->
        <div class="stats-grid">
            <div class="stat-card gradient-purple">
                <div class="stat-icon">
                    <i class="fas fa-users"></i>
                </div>
                <div class="stat-content">
                    <h3><?php echo $stats['total_clients']; ?></h3>
                    <p>Total Clients</p>
                </div>
            </div>
            <div class="stat-card gradient-green">
                <div class="stat-icon">
                    <i class="fas fa-check-circle"></i>
                </div>
                <div class="stat-content">
                    <h3><?php echo $stats['paid_this_year']; ?></h3>
                    <p>Paid (<?php echo $current_year; ?>)</p>
                </div>
            </div>
            <div class="stat-card gradient-orange">
                <div class="stat-icon">
                    <i class="fas fa-clock"></i>
                </div>
                <div class="stat-content">
                    <h3><?php echo $stats['pending_payments']; ?></h3>
                    <p>Pending Approval</p>
                </div>
            </div>
            <div class="stat-card gradient-blue">
                <div class="stat-icon">
                    <i class="fas fa-money-bill-wave"></i>
                </div>
                <div class="stat-content">
                    <h3>TZS <?php echo number_format($stats['collected_this_year']); ?></h3>
                    <p>Collected (<?php echo $current_year; ?>)</p>
                </div>
            </div>
        </div>

        <div class="content-grid">
            <!-- Settings Card -->
            <div class="settings-card">
                <div class="card-header-custom">
                    <h3><i class="fas fa-cog"></i> Payment Settings</h3>
                </div>
                <div class="card-body-custom">
                    <form method="POST">
                        <div class="settings-section">
                            <h4><i class="fas fa-user"></i> Basic Account</h4>
                        </div>
                        <div class="form-group">
                            <label>Basic Yearly Fee (TZS)</label>
                            <input type="number" name="yearly_fee" class="form-control"
                                   value="<?php echo $settings['yearly_fee'] ?? 50000; ?>" min="0" step="1000">
                            <small class="form-text text-muted">Amount basic users pay per year</small>
                        </div>

                        <div class="settings-section premium">
                            <h4><i class="fas fa-crown"></i> Premium Account</h4>
                        </div>
                        <div class="form-group">
                            <label>Premium Yearly Fee (TZS)</label>
                            <input type="number" name="premium_yearly_fee" class="form-control"
                                   value="<?php echo $settings['premium_yearly_fee'] ?? 100000; ?>" min="0" step="1000">
                            <small class="form-text text-muted">Amount premium users pay per year</small>
                        </div>
                        <div class="form-group">
                            <label>Max Images per Land</label>
                            <input type="number" name="max_images_per_land" class="form-control"
                                   value="<?php echo $settings['max_images_per_land'] ?? 5; ?>" min="1" max="20">
                            <small class="form-text text-muted">Maximum images premium users can upload per land</small>
                        </div>

                        <div class="settings-section">
                            <h4><i class="fas fa-cog"></i> General Settings</h4>
                        </div>
                        <div class="form-group">
                            <label>Grace Period (Days)</label>
                            <input type="number" name="grace_period_days" class="form-control"
                                   value="<?php echo $settings['grace_period_days'] ?? 30; ?>" min="0" max="365">
                            <small class="form-text text-muted">Days after due date before access is suspended</small>
                        </div>
                        <div class="form-group">
                            <label>Payment Due Month</label>
                            <select name="payment_due_month" class="form-control">
                                <?php
                                $months = ['January', 'February', 'March', 'April', 'May', 'June',
                                           'July', 'August', 'September', 'October', 'November', 'December'];
                                for($m = 1; $m <= 12; $m++):
                                ?>
                                <option value="<?php echo $m; ?>" <?php echo ($settings['payment_due_month'] ?? 1) == $m ? 'selected' : ''; ?>>
                                    <?php echo $months[$m-1]; ?>
                                </option>
                                <?php endfor; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Payment Due Day</label>
                            <input type="number" name="payment_due_day" class="form-control"
                                   value="<?php echo $settings['payment_due_day'] ?? 1; ?>" min="1" max="31">
                        </div>
                        <button type="submit" class="btn-save">
                            <i class="fas fa-save mr-2"></i>Save Settings
                        </button>
                    </form>
                </div>
            </div>

            <!-- Main Content -->
            <div class="main-content-area">
                <?php if(mysqli_num_rows($pending_result) > 0): ?>
                <div class="pending-card">
                    <div class="card-header-custom warning">
                        <h3><i class="fas fa-clock"></i> Pending Payments</h3>
                        <span class="badge"><?php echo mysqli_num_rows($pending_result); ?></span>
                    </div>
                    <div class="card-body-custom">
                        <div class="table-responsive">
                            <table class="table modern-table-compact">
                                <thead>
                                    <tr>
                                        <th>Client</th>
                                        <th>Year</th>
                                        <th>Amount</th>
                                        <th>Recorded By</th>
                                        <th>Date</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while($p = mysqli_fetch_assoc($pending_result)): ?>
                                    <tr>
                                        <td>
                                            <strong><?php echo htmlspecialchars($p['client_name']); ?></strong>
                                            <span class="phone-small"><?php echo htmlspecialchars($p['phone']); ?></span>
                                        </td>
                                        <td><span class="year-badge"><?php echo $p['payment_year']; ?></span></td>
                                        <td><strong>TZS <?php echo number_format($p['amount']); ?></strong></td>
                                        <td><?php echo htmlspecialchars($p['recorded_by_name']); ?></td>
                                        <td><?php echo date('d M Y', strtotime($p['payment_date'])); ?></td>
                                        <td>
                                            <a href="../client_payments.php?client_id=<?php echo $p['client_id']; ?>"
                                               class="btn-action-sm">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <div class="clients-card">
                    <div class="card-header-custom">
                        <h3><i class="fas fa-users"></i> Client Payment Status (<?php echo $current_year; ?>)</h3>
                        <span class="badge"><?php echo mysqli_num_rows($clients_result); ?> clients</span>
                    </div>
                    <div class="card-body-custom">
                        <div class="table-responsive">
                            <table class="table modern-table-compact">
                                <thead>
                                    <tr>
                                        <th>Client</th>
                                        <th>Broker</th>
                                        <th>Last Paid</th>
                                        <th>Total Paid</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while($c = mysqli_fetch_assoc($clients_result)):
                                        $is_paid = $c['last_paid_year'] >= $current_year;
                                    ?>
                                    <tr>
                                        <td>
                                            <strong><?php echo htmlspecialchars($c['full_name']); ?></strong>
                                            <span class="phone-small"><?php echo htmlspecialchars($c['phone']); ?></span>
                                        </td>
                                        <td><?php echo htmlspecialchars($c['broker_name']); ?></td>
                                        <td><?php echo $c['last_paid_year'] ?: 'Never'; ?></td>
                                        <td>TZS <?php echo number_format($c['total_paid'] ?? 0); ?></td>
                                        <td>
                                            <?php if($is_paid): ?>
                                            <span class="status-paid"><i class="fas fa-check"></i> Paid</span>
                                            <?php else: ?>
                                            <span class="status-unpaid"><i class="fas fa-times"></i> Unpaid</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <a href="../client_payments.php?client_id=<?php echo $c['id']; ?>"
                                               class="btn-action-sm green">
                                                <i class="fas fa-money-bill"></i>
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <style>
    /* Page-specific styles */
    .page-header {
        background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
        border-radius: 20px;
        padding: 30px;
        margin-bottom: 30px;
        color: white;
    }

    .page-title h1 {
        font-size: 28px;
        font-weight: 700;
        margin: 0 0 8px 0;
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .page-title p {
        margin: 0;
        opacity: 0.9;
        font-size: 15px;
    }

    .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 20px;
        margin-bottom: 30px;
    }

    .stat-card {
        border-radius: 16px;
        padding: 24px;
        display: flex;
        align-items: center;
        gap: 16px;
        color: white;
        position: relative;
        overflow: hidden;
    }

    .stat-card::before {
        content: '';
        position: absolute;
        top: -50%;
        right: -50%;
        width: 100%;
        height: 100%;
        background: rgba(255,255,255,0.1);
        border-radius: 50%;
    }

    .gradient-purple {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }

    .gradient-green {
        background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
    }

    .gradient-orange {
        background: linear-gradient(135deg, #f5af19 0%, #f59e0b 100%);
    }

    .gradient-blue {
        background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%);
    }

    .stat-card .stat-icon {
        width: 52px;
        height: 52px;
        border-radius: 14px;
        background: rgba(255,255,255,0.2);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 22px;
    }

    .stat-card .stat-content h3 {
        font-size: 24px;
        font-weight: 700;
        margin: 0;
    }

    .stat-card .stat-content p {
        margin: 4px 0 0 0;
        opacity: 0.9;
        font-size: 13px;
    }

    .content-grid {
        display: grid;
        grid-template-columns: 320px 1fr;
        gap: 24px;
    }

    .settings-card, .pending-card, .clients-card {
        background: white;
        border-radius: 16px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.05);
        overflow: hidden;
    }

    .card-header-custom {
        padding: 20px 24px;
        border-bottom: 1px solid #f1f5f9;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .card-header-custom.warning {
        background: linear-gradient(135deg, rgba(251, 191, 36, 0.1) 0%, rgba(245, 158, 11, 0.1) 100%);
        border-left: 4px solid #f59e0b;
    }

    .card-header-custom h3 {
        font-size: 16px;
        font-weight: 600;
        margin: 0;
        color: #1e293b;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .card-header-custom .badge {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        padding: 6px 12px;
        border-radius: 20px;
        color: white;
        font-size: 12px;
        font-weight: 600;
    }

    .card-body-custom {
        padding: 24px;
    }

    .main-content-area {
        display: flex;
        flex-direction: column;
        gap: 24px;
    }

    .pending-card {
        margin-bottom: 0;
    }

    .settings-section {
        margin-bottom: 16px;
        padding: 10px 14px;
        background: #f1f5f9;
        border-radius: 10px;
        border-left: 3px solid #667eea;
    }

    .settings-section.premium {
        background: linear-gradient(135deg, rgba(212, 175, 55, 0.1), rgba(245, 215, 122, 0.1));
        border-left-color: #d4af37;
    }

    .settings-section h4 {
        font-size: 13px;
        font-weight: 600;
        margin: 0;
        color: #1e293b;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .settings-section.premium h4 i {
        color: #d4af37;
    }

    .form-group {
        margin-bottom: 20px;
    }

    .form-group label {
        font-size: 14px;
        font-weight: 600;
        color: #1e293b;
        margin-bottom: 8px;
        display: block;
    }

    .form-control {
        border-radius: 12px;
        border: 2px solid #e2e8f0;
        padding: 12px 16px;
        font-size: 14px;
        transition: all 0.3s ease;
    }

    .form-control:focus {
        border-color: #22c55e;
        box-shadow: 0 0 0 4px rgba(34, 197, 94, 0.1);
    }

    .form-text {
        font-size: 12px;
        margin-top: 6px;
    }

    .btn-save {
        width: 100%;
        padding: 14px;
        background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
        border: none;
        border-radius: 12px;
        color: white;
        font-weight: 600;
        font-size: 15px;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .btn-save:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(34, 197, 94, 0.3);
    }

    .modern-table-compact {
        margin: 0;
    }

    .modern-table-compact thead th {
        background: #f8fafc;
        border: none;
        padding: 12px 16px;
        font-size: 11px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        color: #64748b;
    }

    .modern-table-compact tbody td {
        padding: 12px 16px;
        border-bottom: 1px solid #f1f5f9;
        font-size: 13px;
        vertical-align: middle;
    }

    .modern-table-compact tbody tr:hover {
        background: #f8fafc;
    }

    .phone-small {
        display: block;
        font-size: 11px;
        color: #94a3b8;
    }

    .year-badge {
        display: inline-block;
        padding: 4px 10px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 8px;
        font-size: 12px;
        font-weight: 600;
    }

    .status-paid {
        display: inline-flex;
        align-items: center;
        gap: 4px;
        padding: 4px 10px;
        background: linear-gradient(135deg, rgba(34, 197, 94, 0.15) 0%, rgba(22, 163, 74, 0.15) 100%);
        color: #16a34a;
        border-radius: 8px;
        font-size: 12px;
        font-weight: 600;
    }

    .status-unpaid {
        display: inline-flex;
        align-items: center;
        gap: 4px;
        padding: 4px 10px;
        background: linear-gradient(135deg, rgba(239, 68, 68, 0.15) 0%, rgba(220, 38, 38, 0.15) 100%);
        color: #dc2626;
        border-radius: 8px;
        font-size: 12px;
        font-weight: 600;
    }

    .btn-action-sm {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 32px;
        height: 32px;
        border-radius: 8px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        text-decoration: none;
        transition: all 0.3s ease;
    }

    .btn-action-sm.green {
        background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
    }

    .btn-action-sm:hover {
        color: white;
        transform: translateY(-2px);
    }

    .alert {
        border: none;
        border-radius: 14px;
        padding: 16px 20px;
        margin-bottom: 25px;
    }

    .alert-success {
        background: linear-gradient(135deg, rgba(34, 197, 94, 0.1) 0%, rgba(22, 163, 74, 0.1) 100%);
        color: #166534;
        border-left: 4px solid #22c55e;
    }

    .alert-danger {
        background: linear-gradient(135deg, rgba(239, 68, 68, 0.1) 0%, rgba(220, 38, 38, 0.1) 100%);
        color: #991b1b;
        border-left: 4px solid #ef4444;
    }

    @media (max-width: 1024px) {
        .content-grid {
            grid-template-columns: 1fr;
        }

        .settings-card {
            order: 1;
        }

        .main-content-area {
            order: 0;
        }
    }

    @media (max-width: 768px) {
        .page-header {
            padding: 20px;
        }

        .page-title h1 {
            font-size: 22px;
        }

        .stats-grid {
            grid-template-columns: 1fr 1fr;
        }

        .stat-card {
            padding: 18px;
        }

        .stat-card .stat-icon {
            width: 44px;
            height: 44px;
            font-size: 18px;
        }

        .stat-card .stat-content h3 {
            font-size: 18px;
        }

        .card-body-custom {
            padding: 16px;
        }
    }
    </style>

    <script src="../assets/vendor/jquery/jquery.min.js"></script>
    <script src="../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>
