<?php
/**
 * Account Settings
 * LandSales Pro - User profile and company settings
 */
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'];
$errors = [];
$success = false;

// Get user details
$user = db_fetch_one("SELECT * FROM users WHERE id = ?", 'i', [$userId]);

// Get subscription
$subscription = db_fetch_one("SELECT s.*, p.name as plan_name, p.max_projects, p.max_plots, p.max_agents
    FROM subscriptions s
    JOIN plans p ON s.plan_id = p.id
    WHERE s.user_id = ? AND s.status = 'active'
    ORDER BY s.expires_at DESC LIMIT 1", 'i', [$userId]);

// Get usage stats
$usage = [
    'projects' => db_fetch_one("SELECT COUNT(*) as count FROM projects WHERE user_id = ?", 'i', [$userId])['count'],
    'plots' => db_fetch_one("SELECT COUNT(*) as count FROM plots WHERE user_id = ?", 'i', [$userId])['count'],
    'agents' => db_fetch_one("SELECT COUNT(*) as count FROM agents WHERE user_id = ?", 'i', [$userId])['count']
];

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

    if ($action === 'profile') {
        $fullName = trim($_POST['full_name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');

        if (empty($fullName)) $errors[] = "Full name is required";
        if (empty($email)) $errors[] = "Email is required";
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Invalid email format";

        // Check email uniqueness
        if (empty($errors)) {
            $existing = db_fetch_one("SELECT id FROM users WHERE email = ? AND id != ?", 'si', [$email, $userId]);
            if ($existing) $errors[] = "Email is already in use";
        }

        if (empty($errors)) {
            db_execute("UPDATE users SET full_name = ?, email = ?, phone = ? WHERE id = ?", 'sssi', [$fullName, $email, $phone, $userId]);
            $_SESSION['user_name'] = $fullName;
            setFlashMessage('success', 'Profile updated successfully!');
            header('Location: index.php');
            exit;
        }
    }

    if ($action === 'company') {
        $companyName = trim($_POST['company_name'] ?? '');
        $companyPhone = trim($_POST['company_phone'] ?? '');
        $companyEmail = trim($_POST['company_email'] ?? '');
        $companyAddress = trim($_POST['company_address'] ?? '');

        db_execute("UPDATE users SET company_name = ?, company_phone = ?, company_email = ?, company_address = ? WHERE id = ?",
            'ssssi', [$companyName, $companyPhone, $companyEmail, $companyAddress, $userId]);
        setFlashMessage('success', 'Company information updated successfully!');
        header('Location: index.php');
        exit;
    }

    if ($action === 'password') {
        $currentPassword = $_POST['current_password'] ?? '';
        $newPassword = $_POST['new_password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';

        if (empty($currentPassword)) $errors[] = "Current password is required";
        if (empty($newPassword)) $errors[] = "New password is required";
        if (strlen($newPassword) < 8) $errors[] = "New password must be at least 8 characters";
        if ($newPassword !== $confirmPassword) $errors[] = "Passwords do not match";

        if (empty($errors)) {
            if (!password_verify($currentPassword, $user['password'])) {
                $errors[] = "Current password is incorrect";
            } else {
                $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
                db_execute("UPDATE users SET password = ? WHERE id = ?", 'si', [$hashedPassword, $userId]);
                setFlashMessage('success', 'Password changed successfully!');
                header('Location: index.php');
                exit;
            }
        }
    }

    // Refresh user data after POST
    $user = db_fetch_one("SELECT * FROM users WHERE id = ?", 'i', [$userId]);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Settings - <?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">
        <div class="top-header">
            <button class="menu-toggle" onclick="toggleSidebar()">
                <i class="fas fa-bars"></i>
            </button>
            <h1 class="page-title">Settings</h1>
        </div>

        <div class="content-wrapper">
            <?php $flash = getFlashMessage(); if ($flash): ?>
            <div class="alert alert-<?php echo $flash['type'] === 'success' ? 'success' : 'danger'; ?>">
                <i class="fas fa-<?php echo $flash['type'] === 'success' ? 'check-circle' : 'exclamation-circle'; ?>"></i>
                <?php echo htmlspecialchars($flash['message']); ?>
            </div>
            <?php endif; ?>

            <?php if (!empty($errors)): ?>
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-circle"></i>
                <ul>
                    <?php foreach ($errors as $error): ?>
                    <li><?php echo htmlspecialchars($error); ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
            <?php endif; ?>

            <div class="settings-grid">
                <!-- Subscription Card -->
                <div class="card subscription-card">
                    <div class="card-header">
                        <h3><i class="fas fa-crown"></i> Subscription</h3>
                    </div>
                    <div class="card-body">
                        <?php if ($subscription): ?>
                        <div class="plan-badge"><?php echo htmlspecialchars($subscription['plan_name']); ?></div>
                        <div class="subscription-info">
                            <div class="info-row">
                                <span>Status:</span>
                                <span class="badge badge-<?php echo $subscription['status']; ?>"><?php echo ucfirst($subscription['status']); ?></span>
                            </div>
                            <div class="info-row">
                                <span>Expires:</span>
                                <span><?php echo date('F j, Y', strtotime($subscription['expires_at'])); ?></span>
                            </div>
                            <div class="info-row">
                                <span>Days Left:</span>
                                <span><?php
                                    $daysLeft = max(0, ceil((strtotime($subscription['expires_at']) - time()) / 86400));
                                    echo $daysLeft . ' days';
                                ?></span>
                            </div>
                        </div>

                        <h4>Usage</h4>
                        <div class="usage-bars">
                            <div class="usage-item">
                                <div class="usage-label">
                                    <span>Projects</span>
                                    <span><?php echo $usage['projects']; ?>/<?php echo $subscription['max_projects'] ?: '∞'; ?></span>
                                </div>
                                <div class="usage-bar">
                                    <div class="usage-fill" style="width: <?php echo $subscription['max_projects'] ? min(100, ($usage['projects'] / $subscription['max_projects']) * 100) : 10; ?>%"></div>
                                </div>
                            </div>
                            <div class="usage-item">
                                <div class="usage-label">
                                    <span>Plots</span>
                                    <span><?php echo $usage['plots']; ?>/<?php echo $subscription['max_plots'] ?: '∞'; ?></span>
                                </div>
                                <div class="usage-bar">
                                    <div class="usage-fill" style="width: <?php echo $subscription['max_plots'] ? min(100, ($usage['plots'] / $subscription['max_plots']) * 100) : 10; ?>%"></div>
                                </div>
                            </div>
                            <div class="usage-item">
                                <div class="usage-label">
                                    <span>Agents</span>
                                    <span><?php echo $usage['agents']; ?>/<?php echo $subscription['max_agents'] ?: '∞'; ?></span>
                                </div>
                                <div class="usage-bar">
                                    <div class="usage-fill" style="width: <?php echo $subscription['max_agents'] ? min(100, ($usage['agents'] / $subscription['max_agents']) * 100) : 10; ?>%"></div>
                                </div>
                            </div>
                        </div>

                        <a href="subscription.php" class="btn btn-primary btn-block">
                            <i class="fas fa-arrow-up"></i> Manage Subscription
                        </a>
                        <?php else: ?>
                        <p class="text-muted">No active subscription</p>
                        <a href="subscription.php" class="btn btn-primary btn-block">Subscribe Now</a>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="settings-forms">
                    <!-- Profile Form -->
                    <form method="POST" class="card">
                        <input type="hidden" name="action" value="profile">
                        <div class="card-header">
                            <h3><i class="fas fa-user"></i> Profile Information</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label for="full_name">Full Name *</label>
                                <input type="text" name="full_name" id="full_name" class="form-control"
                                       value="<?php echo htmlspecialchars($user['full_name']); ?>" required>
                            </div>
                            <div class="form-row">
                                <div class="form-group">
                                    <label for="email">Email Address *</label>
                                    <input type="email" name="email" id="email" class="form-control"
                                           value="<?php echo htmlspecialchars($user['email']); ?>" required>
                                </div>
                                <div class="form-group">
                                    <label for="phone">Phone Number</label>
                                    <input type="tel" name="phone" id="phone" class="form-control"
                                           value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>">
                                </div>
                            </div>
                        </div>
                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> Save Profile
                            </button>
                        </div>
                    </form>

                    <!-- Company Form -->
                    <form method="POST" class="card">
                        <input type="hidden" name="action" value="company">
                        <div class="card-header">
                            <h3><i class="fas fa-building"></i> Company Information</h3>
                            <span class="badge">For receipts & documents</span>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label for="company_name">Company Name</label>
                                <input type="text" name="company_name" id="company_name" class="form-control"
                                       value="<?php echo htmlspecialchars($user['company_name'] ?? ''); ?>"
                                       placeholder="Your company name">
                            </div>
                            <div class="form-row">
                                <div class="form-group">
                                    <label for="company_phone">Company Phone</label>
                                    <input type="tel" name="company_phone" id="company_phone" class="form-control"
                                           value="<?php echo htmlspecialchars($user['company_phone'] ?? ''); ?>">
                                </div>
                                <div class="form-group">
                                    <label for="company_email">Company Email</label>
                                    <input type="email" name="company_email" id="company_email" class="form-control"
                                           value="<?php echo htmlspecialchars($user['company_email'] ?? ''); ?>">
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="company_address">Company Address</label>
                                <textarea name="company_address" id="company_address" class="form-control" rows="2"><?php echo htmlspecialchars($user['company_address'] ?? ''); ?></textarea>
                            </div>
                        </div>
                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> Save Company Info
                            </button>
                        </div>
                    </form>

                    <!-- Password Form -->
                    <form method="POST" class="card">
                        <input type="hidden" name="action" value="password">
                        <div class="card-header">
                            <h3><i class="fas fa-lock"></i> Change Password</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label for="current_password">Current Password *</label>
                                <input type="password" name="current_password" id="current_password" class="form-control" required>
                            </div>
                            <div class="form-row">
                                <div class="form-group">
                                    <label for="new_password">New Password *</label>
                                    <input type="password" name="new_password" id="new_password" class="form-control"
                                           minlength="8" required>
                                </div>
                                <div class="form-group">
                                    <label for="confirm_password">Confirm Password *</label>
                                    <input type="password" name="confirm_password" id="confirm_password" class="form-control" required>
                                </div>
                            </div>
                        </div>
                        <div class="card-footer">
                            <button type="submit" class="btn btn-outline">
                                <i class="fas fa-key"></i> Change Password
                            </button>
                        </div>
                    </form>
                </div>
            </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-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .btn-outline { border: 1px solid #e2e8f0; background: white; color: #64748b; }
        .btn-block { width: 100%; justify-content: center; margin-top: 1rem; }

        .alert { padding: 1rem 1.5rem; border-radius: 10px; margin-bottom: 1.5rem; display: flex; align-items: flex-start; gap: 0.75rem; }
        .alert-success { background: #dcfce7; border: 1px solid #86efac; color: #166534; }
        .alert-danger { background: #fef2f2; border: 1px solid #fecaca; color: #991b1b; }
        .alert ul { margin: 0; padding-left: 1rem; }

        .settings-grid { display: grid; grid-template-columns: 320px 1fr; gap: 1.5rem; }

        .card { background: white; border-radius: 14px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); overflow: hidden; margin-bottom: 1.5rem; }
        .card-header { padding: 1rem 1.5rem; 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; }
        .card-body { padding: 1.5rem; }
        .card-footer { padding: 1rem 1.5rem; border-top: 1px solid #f1f5f9; display: flex; justify-content: flex-end; }

        .subscription-card .card-header h3 i { color: #f59e0b; }

        .plan-badge { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 0.5rem 1rem; border-radius: 8px; font-weight: 600; display: inline-block; margin-bottom: 1rem; }

        .subscription-info { margin-bottom: 1.5rem; }
        .info-row { display: flex; justify-content: space-between; padding: 0.5rem 0; border-bottom: 1px solid #f1f5f9; }
        .info-row:last-child { border-bottom: none; }
        .info-row span:first-child { color: #64748b; }

        .badge { padding: 0.25rem 0.5rem; border-radius: 4px; font-size: 0.7rem; font-weight: 600; }
        .badge-active { background: #dcfce7; color: #16a34a; }
        .badge-expired { background: #fee2e2; color: #dc2626; }

        .card-body h4 { font-size: 0.85rem; color: #64748b; margin: 0 0 0.75rem; }

        .usage-bars { }
        .usage-item { margin-bottom: 0.75rem; }
        .usage-label { display: flex; justify-content: space-between; font-size: 0.8rem; margin-bottom: 0.25rem; }
        .usage-bar { height: 6px; background: #e2e8f0; border-radius: 3px; overflow: hidden; }
        .usage-fill { height: 100%; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 3px; }

        .text-muted { color: #94a3b8; }

        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
        .form-group { margin-bottom: 1rem; }
        .form-group:last-child { margin-bottom: 0; }
        .form-group label { display: block; margin-bottom: 0.5rem; font-weight: 500; color: #374151; font-size: 0.875rem; }
        .form-control { width: 100%; padding: 0.75rem 1rem; border: 1px solid #e2e8f0; border-radius: 8px; font-size: 0.9rem; transition: all 0.2s; box-sizing: border-box; }
        .form-control:focus { outline: none; border-color: #667eea; box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1); }
        textarea.form-control { resize: vertical; min-height: 70px; }

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

        @media (max-width: 576px) {
            .form-row { grid-template-columns: 1fr; }
        }
    </style>
</body>
</html>
