<?php
/**
 * Upgrade to Premium Account
 * Allows basic users to view premium benefits and request upgrade
 */

define('APP_RUNNING', true);
require_once 'db_connect.php';
require_once 'includes/auth.php';

initSecureSession();

if(!isAuthenticated() || !validateSession()) {
    header('Location: login');
    exit;
}

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

// Get user info
$user = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM users WHERE id = $user_id"));
$is_premium = ($user['user_type'] ?? 'basic') == 'premium';

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

$basic_yearly_fee = $settings['yearly_fee'] ?? 50000;
$premium_yearly_fee = $settings['premium_yearly_fee'] ?? 100000;
$max_images_per_land = $settings['max_images_per_land'] ?? 5;

// If user has custom premium amount, use that
$user_premium_fee = $user['premium_amount'] ?? $premium_yearly_fee;

// Calculate upgrade fee (difference if already paid basic)
$current_year = date('Y');
$registration_date = $user['subscription_start_date'] ?: date('Y-m-d', strtotime($user['created_at']));
$registration_year = date('Y', strtotime($registration_date));

// Check if user has paid basic fee for current year
$paid_basic = mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT * FROM user_payments WHERE user_id = $user_id AND payment_year = $current_year AND status = 'confirmed'"
));

$upgrade_fee = $user_premium_fee;
if($paid_basic && !$is_premium) {
    // If they've paid basic, they only need to pay the difference
    $upgrade_fee = max(0, $user_premium_fee - $paid_basic['amount']);
}

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

// Handle upgrade request
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['request_upgrade'])) {
    $phone = mysqli_real_escape_string($conn, trim($_POST['contact_phone']));
    $notes = mysqli_real_escape_string($conn, trim($_POST['notes']));

    // Create an upgrade request (activity log entry)
    $log_sql = "INSERT INTO activity_logs (user_id, action, details, ip_address) VALUES (?, 'premium_upgrade_request', ?, ?)";
    $stmt = mysqli_prepare($conn, $log_sql);
    $details = json_encode([
        'user_id' => $user_id,
        'contact_phone' => $phone,
        'notes' => $notes,
        'requested_at' => date('Y-m-d H:i:s'),
        'upgrade_fee' => $upgrade_fee
    ]);
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    mysqli_stmt_bind_param($stmt, 'iss', $user_id, $details, $ip);

    if(mysqli_stmt_execute($stmt)) {
        $success = 'Your upgrade request has been submitted! Our team will contact you shortly to complete the payment process.';

        // Send notification email to admin (optional)
        $admin_email = 'info@landsecure.co.tz';
        $subject = 'New Premium Upgrade Request - ' . $user['full_name'];
        $message = "A user has requested to upgrade to Premium:\n\n";
        $message .= "Name: " . $user['full_name'] . "\n";
        $message .= "Email: " . $user['email'] . "\n";
        $message .= "Phone: " . $phone . "\n";
        $message .= "Upgrade Fee: TZS " . number_format($upgrade_fee) . "\n";
        $message .= "Notes: " . $notes . "\n";
        @mail($admin_email, $subject, $message, "From: noreply@landsecure.co.tz");
    } else {
        $error = 'Failed to submit request. Please try again.';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upgrade to Premium - LandSecure</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Playfair+Display:wght@600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/font-awesome/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Inter', sans-serif; }
        :root {
            --primary: #1a3a6e;
            --secondary: #2d5a3d;
            --gold: #d4af37;
            --gold-light: #f5d77a;
            --success: #22c55e;
            --gray-50: #f8fafc;
            --gray-100: #f1f5f9;
            --gray-200: #e2e8f0;
            --gray-500: #64748b;
            --gray-700: #334155;
            --gray-800: #1e293b;
            --sidebar-width: 280px;
        }
        body { background: var(--gray-100); min-height: 100vh; }
        .app-main { margin-left: var(--sidebar-width); padding: 24px; }
        @media (max-width: 1024px) { .app-main { margin-left: 0; padding: 16px; padding-top: 80px; } }

        .back-link {
            display: inline-flex; align-items: center; gap: 8px;
            color: var(--gray-500); text-decoration: none; font-size: 14px; margin-bottom: 20px;
        }
        .back-link:hover { color: var(--primary); }

        /* Page Header */
        .page-header {
            background: linear-gradient(135deg, var(--gold) 0%, var(--gold-light) 100%);
            border-radius: 20px;
            padding: 40px;
            margin-bottom: 30px;
            color: var(--primary);
            position: relative;
            overflow: hidden;
        }

        .page-header::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -20%;
            width: 60%;
            height: 200%;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 50%;
        }

        .page-header h1 {
            font-family: 'Playfair Display', serif;
            font-size: 32px;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .page-header p {
            font-size: 16px;
            opacity: 0.9;
        }

        .crown-badge {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            background: var(--primary);
            color: var(--gold);
            padding: 10px 20px;
            border-radius: 30px;
            font-weight: 600;
            margin-top: 15px;
        }

        /* Alert */
        .alert {
            padding: 16px 20px;
            border-radius: 12px;
            margin-bottom: 24px;
            display: flex;
            align-items: center;
            gap: 12px;
        }
        .alert-success { background: rgba(34, 197, 94, 0.1); color: #166534; border-left: 4px solid var(--success); }
        .alert-danger { background: rgba(239, 68, 68, 0.1); color: #991b1b; border-left: 4px solid #ef4444; }
        .alert-info { background: rgba(59, 130, 246, 0.1); color: #1e40af; border-left: 4px solid #3b82f6; }

        /* Comparison Cards */
        .comparison-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
            gap: 24px;
            margin-bottom: 30px;
        }

        .plan-card {
            background: white;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            position: relative;
            transition: transform 0.3s, box-shadow 0.3s;
        }

        .plan-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 12px 40px rgba(0, 0, 0, 0.12);
        }

        .plan-card.premium {
            border: 3px solid var(--gold);
        }

        .plan-card.premium::before {
            content: 'RECOMMENDED';
            position: absolute;
            top: 15px;
            right: -30px;
            background: linear-gradient(135deg, var(--gold), var(--gold-light));
            color: var(--primary);
            padding: 5px 40px;
            font-size: 11px;
            font-weight: 700;
            transform: rotate(45deg);
        }

        .plan-header {
            padding: 30px;
            text-align: center;
        }

        .plan-card.basic .plan-header {
            background: linear-gradient(135deg, var(--gray-100), var(--gray-200));
        }

        .plan-card.premium .plan-header {
            background: linear-gradient(135deg, var(--gold), var(--gold-light));
            color: var(--primary);
        }

        .plan-icon {
            width: 70px;
            height: 70px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 15px;
            font-size: 28px;
        }

        .plan-card.basic .plan-icon {
            background: white;
            color: var(--gray-500);
        }

        .plan-card.premium .plan-icon {
            background: var(--primary);
            color: var(--gold);
        }

        .plan-name {
            font-size: 24px;
            font-weight: 700;
            margin-bottom: 5px;
        }

        .plan-price {
            font-family: 'Playfair Display', serif;
            font-size: 36px;
            font-weight: 700;
        }

        .plan-price span {
            font-size: 14px;
            font-weight: 400;
            opacity: 0.8;
        }

        .plan-body {
            padding: 30px;
        }

        .plan-features {
            list-style: none;
        }

        .plan-features li {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 0;
            border-bottom: 1px solid var(--gray-100);
            font-size: 14px;
            color: var(--gray-700);
        }

        .plan-features li:last-child {
            border-bottom: none;
        }

        .plan-features li i {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
        }

        .plan-features li i.fa-check {
            background: rgba(34, 197, 94, 0.15);
            color: var(--success);
        }

        .plan-features li i.fa-times {
            background: rgba(239, 68, 68, 0.15);
            color: #ef4444;
        }

        .plan-features li i.fa-crown {
            background: linear-gradient(135deg, var(--gold), var(--gold-light));
            color: var(--primary);
        }

        .plan-footer {
            padding: 0 30px 30px;
        }

        .btn-plan {
            width: 100%;
            padding: 14px;
            border: none;
            border-radius: 12px;
            font-size: 15px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-plan.basic {
            background: var(--gray-200);
            color: var(--gray-600);
        }

        .btn-plan.premium {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: white;
        }

        .btn-plan.premium:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(26, 58, 110, 0.3);
        }

        .btn-plan:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        /* Upgrade Request Form */
        .upgrade-card {
            background: white;
            border-radius: 20px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            overflow: hidden;
            margin-bottom: 30px;
        }

        .upgrade-card-header {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: white;
            padding: 24px 30px;
        }

        .upgrade-card-header h3 {
            font-size: 20px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .upgrade-card-body {
            padding: 30px;
        }

        .upgrade-summary {
            background: var(--gray-50);
            border-radius: 16px;
            padding: 24px;
            margin-bottom: 24px;
        }

        .summary-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid var(--gray-200);
        }

        .summary-row:last-child {
            border-bottom: none;
            padding-top: 16px;
        }

        .summary-row.total {
            font-size: 18px;
            font-weight: 700;
            color: var(--primary);
        }

        .summary-label {
            color: var(--gray-500);
        }

        .summary-value {
            font-weight: 600;
            color: var(--gray-800);
        }

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

        .form-label {
            display: block;
            font-size: 14px;
            font-weight: 600;
            color: var(--gray-700);
            margin-bottom: 8px;
        }

        .form-control {
            width: 100%;
            padding: 14px 18px;
            border: 2px solid var(--gray-200);
            border-radius: 12px;
            font-size: 15px;
            transition: all 0.3s;
        }

        .form-control:focus {
            outline: none;
            border-color: var(--gold);
            box-shadow: 0 0 0 4px rgba(212, 175, 55, 0.1);
        }

        .btn-upgrade {
            width: 100%;
            padding: 16px;
            background: linear-gradient(135deg, var(--gold), var(--gold-light));
            color: var(--primary);
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 700;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            transition: all 0.3s;
        }

        .btn-upgrade:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(212, 175, 55, 0.4);
        }

        .already-premium {
            text-align: center;
            padding: 40px;
        }

        .already-premium .icon {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--gold), var(--gold-light));
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
            font-size: 40px;
            color: var(--primary);
        }

        .already-premium h3 {
            font-family: 'Playfair Display', serif;
            font-size: 24px;
            color: var(--gray-800);
            margin-bottom: 10px;
        }

        .already-premium p {
            color: var(--gray-500);
            margin-bottom: 20px;
        }

        /* Payment Info */
        .payment-info {
            background: linear-gradient(135deg, rgba(59, 130, 246, 0.1), rgba(37, 99, 235, 0.1));
            border: 1px solid rgba(59, 130, 246, 0.3);
            border-radius: 12px;
            padding: 20px;
            margin-top: 20px;
        }

        .payment-info h4 {
            color: #1e40af;
            margin-bottom: 12px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .payment-info p {
            color: #1e40af;
            font-size: 14px;
            margin: 0;
        }

        .payment-info ul {
            margin: 10px 0 0 20px;
            color: #1e40af;
            font-size: 14px;
        }

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

            .page-header h1 {
                font-size: 24px;
            }

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

            .plan-card.premium::before {
                display: none;
            }
        }
    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="app-main">
        <a href="<?php echo url('dashboard'); ?>" class="back-link">
            <i class="fas fa-arrow-left"></i> Back to Dashboard
        </a>

        <div class="page-header">
            <h1><i class="fas fa-crown"></i> Upgrade to Premium</h1>
            <p>Unlock exclusive features and get the most out of LandSecure</p>
            <?php if($is_premium): ?>
            <div class="crown-badge">
                <i class="fas fa-crown"></i> You're a Premium Member
            </div>
            <?php endif; ?>
        </div>

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

        <?php if($success): ?>
        <div class="alert alert-success"><i class="fas fa-check-circle"></i> <?php echo $success; ?></div>
        <?php endif; ?>

        <!-- Plan Comparison -->
        <div class="comparison-grid">
            <!-- Basic Plan -->
            <div class="plan-card basic">
                <div class="plan-header">
                    <div class="plan-icon">
                        <i class="fas fa-user"></i>
                    </div>
                    <h3 class="plan-name">Basic</h3>
                    <div class="plan-price">
                        TZS <?php echo number_format($basic_yearly_fee); ?> <span>/year</span>
                    </div>
                </div>
                <div class="plan-body">
                    <ul class="plan-features">
                        <li><i class="fas fa-check"></i> Register unlimited lands</li>
                        <li><i class="fas fa-check"></i> Add beacon points</li>
                        <li><i class="fas fa-check"></i> View land boundaries</li>
                        <li><i class="fas fa-check"></i> Share lands with others</li>
                        <li><i class="fas fa-check"></i> Digital certificates</li>
                        <li><i class="fas fa-times"></i> Upload land images</li>
                        <li><i class="fas fa-times"></i> Priority support</li>
                        <li><i class="fas fa-times"></i> Premium badge</li>
                    </ul>
                </div>
                <div class="plan-footer">
                    <button class="btn-plan basic" disabled>
                        <?php echo (!$is_premium) ? 'Current Plan' : 'Basic Plan'; ?>
                    </button>
                </div>
            </div>

            <!-- Premium Plan -->
            <div class="plan-card premium">
                <div class="plan-header">
                    <div class="plan-icon">
                        <i class="fas fa-crown"></i>
                    </div>
                    <h3 class="plan-name">Premium</h3>
                    <div class="plan-price">
                        TZS <?php echo number_format($user_premium_fee); ?> <span>/year</span>
                    </div>
                </div>
                <div class="plan-body">
                    <ul class="plan-features">
                        <li><i class="fas fa-check"></i> Register unlimited lands</li>
                        <li><i class="fas fa-check"></i> Add beacon points</li>
                        <li><i class="fas fa-check"></i> View land boundaries</li>
                        <li><i class="fas fa-check"></i> Share lands with others</li>
                        <li><i class="fas fa-check"></i> Digital certificates</li>
                        <li><i class="fas fa-crown"></i> Upload up to <?php echo $max_images_per_land; ?> images per land</li>
                        <li><i class="fas fa-crown"></i> Priority support</li>
                        <li><i class="fas fa-crown"></i> Premium badge on certificate</li>
                    </ul>
                </div>
                <div class="plan-footer">
                    <?php if($is_premium): ?>
                    <button class="btn-plan premium" disabled>
                        <i class="fas fa-check-circle"></i> Your Current Plan
                    </button>
                    <?php else: ?>
                    <button class="btn-plan premium" onclick="document.getElementById('upgradeForm').scrollIntoView({behavior: 'smooth'})">
                        <i class="fas fa-arrow-up"></i> Upgrade Now
                    </button>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <?php if($is_premium): ?>
        <!-- Already Premium -->
        <div class="upgrade-card">
            <div class="upgrade-card-body">
                <div class="already-premium">
                    <div class="icon">
                        <i class="fas fa-crown"></i>
                    </div>
                    <h3>You're Already Premium!</h3>
                    <p>Thank you for being a premium member. Enjoy all the exclusive features.</p>
                    <a href="<?php echo url('user-payments'); ?>" class="btn-upgrade" style="max-width: 300px; margin: 0 auto;">
                        <i class="fas fa-receipt"></i> View Payment History
                    </a>
                </div>
            </div>
        </div>
        <?php else: ?>
        <!-- Upgrade Form -->
        <div class="upgrade-card" id="upgradeForm">
            <div class="upgrade-card-header">
                <h3><i class="fas fa-arrow-circle-up"></i> Request Upgrade</h3>
            </div>
            <div class="upgrade-card-body">
                <div class="upgrade-summary">
                    <div class="summary-row">
                        <span class="summary-label">Account Type</span>
                        <span class="summary-value">Basic to Premium</span>
                    </div>
                    <div class="summary-row">
                        <span class="summary-label">Premium Fee</span>
                        <span class="summary-value">TZS <?php echo number_format($user_premium_fee); ?>/year</span>
                    </div>
                    <?php if($paid_basic): ?>
                    <div class="summary-row">
                        <span class="summary-label">Already Paid (Basic)</span>
                        <span class="summary-value">- TZS <?php echo number_format($paid_basic['amount']); ?></span>
                    </div>
                    <?php endif; ?>
                    <div class="summary-row total">
                        <span class="summary-label">Upgrade Fee</span>
                        <span class="summary-value">TZS <?php echo number_format($upgrade_fee); ?></span>
                    </div>
                </div>

                <form method="POST">
                    <input type="hidden" name="request_upgrade" value="1">

                    <div class="form-group">
                        <label class="form-label">Contact Phone Number *</label>
                        <input type="tel" name="contact_phone" class="form-control"
                               value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>"
                               placeholder="+255 XXX XXX XXX" required>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Additional Notes (Optional)</label>
                        <textarea name="notes" class="form-control" rows="3"
                                  placeholder="Any specific requests or questions..."></textarea>
                    </div>

                    <button type="submit" class="btn-upgrade">
                        <i class="fas fa-paper-plane"></i> Submit Upgrade Request
                    </button>

                    <div class="payment-info">
                        <h4><i class="fas fa-info-circle"></i> Payment Information</h4>
                        <p>After submitting your request:</p>
                        <ul>
                            <li>Our team will contact you within 24 hours</li>
                            <li>You can pay via Mobile Money, Bank Transfer, or Cash</li>
                            <li>Your account will be upgraded immediately after payment confirmation</li>
                        </ul>
                    </div>
                </form>
            </div>
        </div>
        <?php endif; ?>
    </main>
</body>
</html>
