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

initSecureSession();

if(!isset($_SESSION['user_id'])) {
    header('Location: login');
    exit;
}

$user_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

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

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    if(isset($_POST['update_profile'])) {
        $full_name = trim($_POST['full_name']);
        $email = trim($_POST['email']);
        $phone = trim($_POST['phone']);

        // Check email uniqueness
        $check_stmt = $conn->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
        $check_stmt->bind_param("si", $email, $user_id);
        $check_stmt->execute();

        if($check_stmt->get_result()->num_rows > 0) {
            $error = 'Email already in use by another account';
        } else {
            $update_stmt = $conn->prepare("UPDATE users SET full_name = ?, email = ?, phone = ? WHERE id = ?");
            $update_stmt->bind_param("sssi", $full_name, $email, $phone, $user_id);
            $update_stmt->execute();

            $_SESSION['full_name'] = $full_name;
            $_SESSION['email'] = $email;
            $success = 'Profile updated successfully';

            // Refresh user data
            $stmt->execute();
            $user = $stmt->get_result()->fetch_assoc();
        }
    } elseif(isset($_POST['change_password'])) {
        $current = $_POST['current_password'];
        $new = $_POST['new_password'];
        $confirm = $_POST['confirm_password'];

        if(!password_verify($current, $user['password'])) {
            $error = 'Current password is incorrect';
        } elseif(strlen($new) < 6) {
            $error = 'New password must be at least 6 characters';
        } elseif($new !== $confirm) {
            $error = 'New passwords do not match';
        } else {
            $hashed = password_hash($new, PASSWORD_DEFAULT);
            $pwd_stmt = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
            $pwd_stmt->bind_param("si", $hashed, $user_id);
            $pwd_stmt->execute();
            $success = 'Password changed successfully';
        }
    }
}

// Get user statistics
$user_role = $_SESSION['role'] ?? 'user';

// Lands count - brokers can see lands they created or lands of their clients
if($user_role == 'broker') {
    $lands_count = $conn->query("SELECT COUNT(*) as cnt FROM lands WHERE user_id = $user_id OR client_id IN (SELECT id FROM clients WHERE broker_id = $user_id)")->fetch_assoc()['cnt'];
} else {
    $lands_count = $conn->query("SELECT COUNT(*) as cnt FROM lands WHERE user_id = $user_id")->fetch_assoc()['cnt'];
}

// Clients count - for brokers
$clients_count = $conn->query("SELECT COUNT(*) as cnt FROM clients WHERE broker_id = $user_id")->fetch_assoc()['cnt'];

// Shared lands count - lands with share_token set
$shared_count = $conn->query("SELECT COUNT(*) as cnt FROM lands WHERE user_id = $user_id AND share_token IS NOT NULL")->fetch_assoc()['cnt'];

$page_title = 'My Profile';
$current_page = 'profile';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?> - Uhakiki Madalali</title>
    <link rel="manifest" href="manifest.json">
    <meta name="theme-color" content="#1a3a6e">
    <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">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
        }

        :root {
            --primary: #1a3a6e;
            --primary-light: #2d5a9e;
            --secondary: #2d5a3d;
            --secondary-light: #3d7a52;
            --accent: #e67e22;
            --danger: #dc3545;
            --success: #28a745;
            --warning: #ffc107;
            --gray-50: #f8fafc;
            --gray-100: #f1f5f9;
            --gray-200: #e2e8f0;
            --gray-300: #cbd5e1;
            --gray-400: #94a3b8;
            --gray-500: #64748b;
            --gray-600: #475569;
            --gray-700: #334155;
            --gray-800: #1e293b;
            --gray-900: #0f172a;
            --sidebar-width: 280px;
            --topbar-height: 70px;
            --shadow-sm: 0 1px 2px rgba(0,0,0,0.05);
            --shadow: 0 4px 6px -1px rgba(0,0,0,0.1);
            --shadow-lg: 0 10px 25px -5px rgba(0,0,0,0.1);
            --shadow-xl: 0 25px 50px -12px rgba(0,0,0,0.15);
            --radius: 12px;
            --radius-lg: 16px;
            --radius-xl: 24px;
        }

        body {
            background: var(--gray-100);
            min-height: 100vh;
        }

        /* Main content area */
        .app-main {
            margin-left: var(--sidebar-width);
            min-height: 100vh;
            transition: margin-left 0.3s ease;
        }

        @media (max-width: 1024px) {
            .app-main {
                margin-left: 0;
            }
        }

        /* Page Header */
        .page-header {
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            padding: 32px 32px 80px;
            color: white;
        }

        .page-header-content {
            max-width: 1400px;
            margin: 0 auto;
        }

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

        .page-subtitle {
            font-size: 15px;
            opacity: 0.9;
        }

        /* Content Container */
        .content-container {
            max-width: 1400px;
            margin: -50px auto 0;
            padding: 0 32px 32px;
            position: relative;
            z-index: 10;
        }

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

            .content-container {
                padding: 0 16px 24px;
            }

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

        /* Stats Cards */
        .stats-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 20px;
            margin-bottom: 24px;
        }

        .stat-card {
            background: white;
            border-radius: var(--radius-lg);
            padding: 20px;
            box-shadow: var(--shadow);
            display: flex;
            align-items: center;
            gap: 16px;
            transition: transform 0.2s, box-shadow 0.2s;
        }

        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-lg);
        }

        .stat-icon {
            width: 52px;
            height: 52px;
            border-radius: var(--radius);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 22px;
            color: white;
        }

        .stat-icon.primary { background: linear-gradient(135deg, var(--primary), var(--primary-light)); }
        .stat-icon.success { background: linear-gradient(135deg, var(--secondary), var(--secondary-light)); }
        .stat-icon.warning { background: linear-gradient(135deg, #f59e0b, #fbbf24); }
        .stat-icon.info { background: linear-gradient(135deg, #0ea5e9, #38bdf8); }

        .stat-content h3 {
            font-size: 26px;
            font-weight: 700;
            color: var(--gray-800);
            line-height: 1;
            margin-bottom: 4px;
        }

        .stat-content p {
            font-size: 13px;
            color: var(--gray-500);
            margin: 0;
        }

        /* Profile Grid */
        .profile-grid {
            display: grid;
            grid-template-columns: 350px 1fr;
            gap: 24px;
            align-items: start;
        }

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

        /* Profile Card */
        .profile-card {
            background: white;
            border-radius: var(--radius-lg);
            box-shadow: var(--shadow);
            overflow: hidden;
        }

        .profile-cover {
            height: 100px;
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            position: relative;
        }

        .profile-avatar {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--primary-light), var(--secondary-light));
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 40px;
            font-weight: 700;
            border: 4px solid white;
            box-shadow: var(--shadow-lg);
            position: absolute;
            bottom: -50px;
            left: 50%;
            transform: translateX(-50%);
        }

        .profile-info {
            padding: 60px 24px 24px;
            text-align: center;
        }

        .profile-name {
            font-size: 22px;
            font-weight: 700;
            color: var(--gray-800);
            margin-bottom: 4px;
        }

        .profile-username {
            font-size: 14px;
            color: var(--gray-500);
            margin-bottom: 16px;
        }

        .profile-details {
            display: flex;
            flex-direction: column;
            gap: 10px;
            padding: 16px 0;
            border-top: 1px solid var(--gray-200);
            margin-top: 8px;
        }

        .profile-detail {
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 14px;
            color: var(--gray-600);
        }

        .profile-detail i {
            width: 20px;
            color: var(--gray-400);
        }

        .profile-meta {
            background: var(--gray-50);
            padding: 16px 24px;
            font-size: 13px;
            color: var(--gray-500);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .role-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 6px 14px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            color: white;
            margin-bottom: 16px;
        }

        /* Form Cards */
        .form-card {
            background: white;
            border-radius: var(--radius-lg);
            box-shadow: var(--shadow);
            overflow: hidden;
            margin-bottom: 24px;
        }

        .form-card:last-child {
            margin-bottom: 0;
        }

        .form-card-header {
            padding: 20px 24px;
            border-bottom: 1px solid var(--gray-200);
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .form-card-header i {
            width: 36px;
            height: 36px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            color: white;
        }

        .form-card-header i.primary {
            background: linear-gradient(135deg, var(--primary), var(--primary-light));
        }

        .form-card-header i.warning {
            background: linear-gradient(135deg, var(--accent), #f39c12);
        }

        .form-card-header h3 {
            font-size: 16px;
            font-weight: 600;
            color: var(--gray-800);
            margin: 0;
        }

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

        /* Form Elements */
        .form-group {
            margin-bottom: 20px;
        }

        .form-group:last-of-type {
            margin-bottom: 0;
        }

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

        .form-control {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid var(--gray-200);
            border-radius: var(--radius);
            font-size: 15px;
            color: var(--gray-800);
            background: white;
            transition: all 0.2s;
        }

        .form-control:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 4px rgba(26, 58, 110, 0.1);
        }

        .form-control::placeholder {
            color: var(--gray-400);
        }

        .input-icon-wrapper {
            position: relative;
        }

        .input-icon-wrapper .form-control {
            padding-left: 44px;
        }

        .input-icon-wrapper i {
            position: absolute;
            left: 16px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--gray-400);
        }

        /* Password strength indicator */
        .password-strength {
            margin-top: 8px;
            display: flex;
            gap: 4px;
        }

        .password-strength span {
            flex: 1;
            height: 4px;
            border-radius: 2px;
            background: var(--gray-200);
            transition: background 0.2s;
        }

        .password-strength.weak span:first-child {
            background: var(--danger);
        }

        .password-strength.medium span:nth-child(-n+2) {
            background: var(--warning);
        }

        .password-strength.strong span {
            background: var(--success);
        }

        /* Buttons */
        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            padding: 12px 24px;
            border-radius: var(--radius);
            font-size: 14px;
            font-weight: 600;
            border: none;
            cursor: pointer;
            transition: all 0.2s;
        }

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

        .btn-primary:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(26, 58, 110, 0.3);
        }

        .btn-warning {
            background: linear-gradient(135deg, var(--accent), #f39c12);
            color: white;
        }

        .btn-warning:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(230, 126, 34, 0.3);
        }

        .form-actions {
            margin-top: 24px;
            padding-top: 20px;
            border-top: 1px solid var(--gray-200);
        }

        /* Alerts */
        .alert {
            padding: 16px 20px;
            border-radius: var(--radius);
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 14px;
            font-weight: 500;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-danger {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .alert i {
            font-size: 18px;
        }

        /* Toast Notification */
        .toast-container {
            position: fixed;
            bottom: 24px;
            right: 24px;
            z-index: 9999;
        }

        .toast {
            background: var(--gray-800);
            color: white;
            padding: 14px 20px;
            border-radius: var(--radius);
            box-shadow: var(--shadow-xl);
            display: flex;
            align-items: center;
            gap: 10px;
            transform: translateY(100px);
            opacity: 0;
            transition: all 0.3s ease;
        }

        .toast.show {
            transform: translateY(0);
            opacity: 1;
        }

        .toast.success {
            background: linear-gradient(135deg, var(--secondary), var(--secondary-light));
        }

        .toast.error {
            background: linear-gradient(135deg, var(--danger), #c82333);
        }

        @media (max-width: 768px) {
            .stats-row {
                grid-template-columns: repeat(2, 1fr);
                gap: 12px;
            }

            .stat-card {
                padding: 16px;
            }

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

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

            .form-card-body {
                padding: 20px;
            }

            .toast-container {
                left: 16px;
                right: 16px;
                bottom: 16px;
            }
        }
    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="app-main">
        <div class="page-header">
            <div class="page-header-content">
                <h1 class="page-title">
                    <i class="fas fa-user-circle"></i>
                    My Profile
                </h1>
                <p class="page-subtitle">Manage your account settings and preferences</p>
            </div>
        </div>

        <div class="content-container">
            <!-- Stats Row -->
            <div class="stats-row">
                <div class="stat-card">
                    <div class="stat-icon primary">
                        <i class="fas fa-map"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($lands_count); ?></h3>
                        <p>My Lands</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon success">
                        <i class="fas fa-users"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($clients_count); ?></h3>
                        <p>Clients</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon info">
                        <i class="fas fa-share-alt"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($shared_count); ?></h3>
                        <p>Shared</p>
                    </div>
                </div>
            </div>

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

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

            <div class="profile-grid">
                <!-- Profile Card -->
                <div class="profile-card">
                    <div class="profile-cover">
                        <div class="profile-avatar">
                            <?php echo strtoupper(substr($user['username'], 0, 1)); ?>
                        </div>
                    </div>
                    <div class="profile-info">
                        <h2 class="profile-name"><?php echo htmlspecialchars($user['full_name'] ?: $user['username']); ?></h2>
                        <p class="profile-username">@<?php echo htmlspecialchars($user['username']); ?></p>

                        <div class="role-badge">
                            <i class="fas fa-shield-alt"></i>
                            <?php echo ucfirst($user['role'] ?? 'User'); ?>
                        </div>

                        <div class="profile-details">
                            <div class="profile-detail">
                                <i class="fas fa-envelope"></i>
                                <span><?php echo htmlspecialchars($user['email']); ?></span>
                            </div>
                            <?php if(!empty($user['phone'])): ?>
                            <div class="profile-detail">
                                <i class="fas fa-phone"></i>
                                <span><?php echo htmlspecialchars($user['phone']); ?></span>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="profile-meta">
                        <i class="fas fa-calendar-alt"></i>
                        Member since <?php echo date('F Y', strtotime($user['created_at'])); ?>
                    </div>
                </div>

                <!-- Forms Column -->
                <div class="forms-column">
                    <!-- Update Profile Form -->
                    <div class="form-card">
                        <div class="form-card-header">
                            <i class="fas fa-user-edit primary"></i>
                            <h3>Update Profile</h3>
                        </div>
                        <div class="form-card-body">
                            <form method="POST" id="profileForm">
                                <div class="form-group">
                                    <label class="form-label">Full Name</label>
                                    <div class="input-icon-wrapper">
                                        <i class="fas fa-user"></i>
                                        <input type="text" name="full_name" class="form-control"
                                               placeholder="Enter your full name"
                                               value="<?php echo htmlspecialchars($user['full_name']); ?>">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">Email Address</label>
                                    <div class="input-icon-wrapper">
                                        <i class="fas fa-envelope"></i>
                                        <input type="email" name="email" class="form-control" required
                                               placeholder="Enter your email"
                                               value="<?php echo htmlspecialchars($user['email']); ?>">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">Phone Number</label>
                                    <div class="input-icon-wrapper">
                                        <i class="fas fa-phone"></i>
                                        <input type="tel" name="phone" class="form-control"
                                               placeholder="Enter your phone number"
                                               value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>">
                                    </div>
                                </div>
                                <div class="form-actions">
                                    <button type="submit" name="update_profile" class="btn btn-primary">
                                        <i class="fas fa-save"></i>
                                        Save Changes
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Change Password Form -->
                    <div class="form-card">
                        <div class="form-card-header">
                            <i class="fas fa-lock warning"></i>
                            <h3>Change Password</h3>
                        </div>
                        <div class="form-card-body">
                            <form method="POST" id="passwordForm">
                                <div class="form-group">
                                    <label class="form-label">Current Password</label>
                                    <div class="input-icon-wrapper">
                                        <i class="fas fa-key"></i>
                                        <input type="password" name="current_password" class="form-control" required
                                               placeholder="Enter current password">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">New Password</label>
                                    <div class="input-icon-wrapper">
                                        <i class="fas fa-lock"></i>
                                        <input type="password" name="new_password" id="newPassword" class="form-control" required
                                               placeholder="Enter new password (min 6 characters)">
                                    </div>
                                    <div class="password-strength" id="passwordStrength">
                                        <span></span>
                                        <span></span>
                                        <span></span>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">Confirm New Password</label>
                                    <div class="input-icon-wrapper">
                                        <i class="fas fa-lock"></i>
                                        <input type="password" name="confirm_password" class="form-control" required
                                               placeholder="Confirm new password">
                                    </div>
                                </div>
                                <div class="form-actions">
                                    <button type="submit" name="change_password" class="btn btn-warning">
                                        <i class="fas fa-key"></i>
                                        Update Password
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- Toast Container -->
    <div class="toast-container">
        <div class="toast" id="toast">
            <i class="fas fa-check-circle"></i>
            <span id="toastMessage">Success!</span>
        </div>
    </div>

    <script src="assets/js/offline-storage.js"></script>
    <script>
        // Register Service Worker
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('/sw.js')
                .then(reg => console.log('Service Worker registered'))
                .catch(err => console.log('Service Worker registration failed:', err));
        }

        // Password strength indicator
        const newPassword = document.getElementById('newPassword');
        const strengthIndicator = document.getElementById('passwordStrength');

        if (newPassword) {
            newPassword.addEventListener('input', function() {
                const password = this.value;
                let strength = 0;

                if (password.length >= 6) strength++;
                if (password.match(/[a-z]/) && password.match(/[A-Z]/)) strength++;
                if (password.match(/[0-9]/) || password.match(/[^a-zA-Z0-9]/)) strength++;

                strengthIndicator.className = 'password-strength';
                if (password.length > 0) {
                    if (strength === 1) strengthIndicator.classList.add('weak');
                    else if (strength === 2) strengthIndicator.classList.add('medium');
                    else if (strength === 3) strengthIndicator.classList.add('strong');
                }
            });
        }

        // Toast notification function
        function showToast(message, type = 'success') {
            const toast = document.getElementById('toast');
            const toastMessage = document.getElementById('toastMessage');

            toast.className = 'toast ' + type;
            toastMessage.textContent = message;
            toast.classList.add('show');

            setTimeout(() => {
                toast.classList.remove('show');
            }, 3000);
        }

        // Show success toast if success message exists
        <?php if($success): ?>
        showToast('<?php echo addslashes($success); ?>', 'success');
        <?php endif; ?>
    </script>
</body>
</html>
