<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header("Location: index");
    exit;
}
require_once 'db.php';

$user_id = $_SESSION['user_id'];
$message = '';
$message_type = '';

// Handle Name Update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    $new_name = trim($_POST['full_name']);
    if (!empty($new_name)) {
        $stmt = $conn->prepare("UPDATE users SET name = ? WHERE id = ?");
        $stmt->bind_param("si", $new_name, $user_id);
        if ($stmt->execute()) {
            $_SESSION['user_name'] = $new_name;
            $message = "Profile updated successfully!";
            $message_type = "success";
        } else {
            $message = "Error updating profile.";
            $message_type = "danger";
        }
        $stmt->close();
    }
}

// Handle Password Update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_password'])) {
    $current_pwd = $_POST['current_password'];
    $new_pwd = $_POST['new_password'];
    $confirm_pwd = $_POST['confirm_password'];

    if ($new_pwd !== $confirm_pwd) {
        $message = "New passwords do not match.";
        $message_type = "danger";
    } else {
        $stmt = $conn->prepare("SELECT password FROM users WHERE id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $user = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if (password_verify($current_pwd, $user['password'])) {
            $hashed_pwd = password_hash($new_pwd, PASSWORD_DEFAULT);
            $update = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
            $update->bind_param("si", $hashed_pwd, $user_id);
            if ($update->execute()) {
                $message = "Password changed successfully!";
                $message_type = "success";
            }
            $update->close();
        } else {
            $message = "Current password is incorrect.";
            $message_type = "danger";
        }
    }
}

// Fetch current info
$stmt = $conn->prepare("SELECT name, email FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user_info = $stmt->get_result()->fetch_assoc();
$stmt->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Account Settings - ConstructCRM</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root { --primary-color: #977C49; --primary-dark: #7a633a; --border-radius: 12px; --header-height: 70px; --nav-width: 260px; --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); }
        body { font-family: 'Inter', sans-serif; background-color: #f5f7fa; }
        .header { background-color: #fff; box-shadow: 0 2px 10px rgba(0,0,0,0.05); position: fixed; top: 0; left: 0; right: 0; height: var(--header-height); z-index: 1000; display: flex; align-items: center; padding: 0 20px; text-decoration: none; }
        .logo { font-weight: 700; font-size: 20px; color: var(--primary-color); text-decoration: none; }
        .mobile-menu-toggle { display: none; background: none; border: none; font-size: 24px; color: var(--primary-color); margin-right: 15px; cursor: pointer; }
        .main-container { display: flex; margin-top: var(--header-height); }
        .sidebar-nav { width: var(--nav-width); background-color: #fff; position: fixed; top: var(--header-height); left: 0; bottom: 0; z-index: 999; border-right: 1px solid #eee; transition: var(--transition); }
        .nav-link { display: flex; align-items: center; padding: 12px 20px; color: #555; text-decoration: none; font-weight: 500; }
        .nav-link.active { background-color: rgba(151, 124, 73, 0.1); color: var(--primary-color); border-left: 4px solid var(--primary-color); }
        .content-wrapper { flex: 1; margin-left: var(--nav-width); padding: 30px; transition: var(--transition); }
        .settings-card { background: #fff; border-radius: var(--border-radius); box-shadow: 0 4px 12px rgba(0,0,0,0.08); margin-bottom: 30px; }
        .card-header { background: #fff; border-bottom: 1px solid #eee; padding: 20px 30px; font-weight: 600; color: #333; }
        .card-body { padding: 30px; }
        .btn-primary { background: var(--primary-color); border-color: var(--primary-color); padding: 10px 25px; }
        .btn-primary:hover { background: var(--primary-dark); border-color: var(--primary-dark); }

        /* Overlay for mobile menu */
        .overlay { display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0, 0, 0, 0.5); z-index: 998; }
        .overlay.show { display: block; }

        @media (max-width: 768px) {
            .mobile-menu-toggle { display: block; }
            .sidebar-nav { transform: translateX(-100%); width: 280px; z-index: 1001; }
            .sidebar-nav.show { transform: translateX(0); }
            .content-wrapper { margin-left: 0; padding: 20px; }
            .header { padding: 0 15px; }
            .logo { font-size: 18px; }
        }
    </style>
</head>
<body>
    <header class="header">
        <button class="mobile-menu-toggle" id="mobileMenuToggle">
            <i class="bi bi-list"></i>
        </button>
        <a href="crmdashboard" class="logo"><img src="./assets/logo.png" alt="ConstructCRM Logo" style="height: 60px; width: 85px;"></a>
    </header>
    <div class="main-container">
        <!-- Overlay for mobile -->
        <div class="overlay" id="overlay"></div>

        <nav class="sidebar-nav" id="sidebarNav">
            <div class="p-3">
                <div class="nav-title text-muted small fw-bold text-uppercase mb-2">Main</div>
                <a href="crmdashboard" class="nav-link"><i class="bi bi-speedometer2 me-2"></i> Dashboard</a>
                
                <a href="profile" class="nav-link"><i class="bi bi-person me-2"></i> Profile</a>
                <a href="settings" class="nav-link active"><i class="bi bi-gear me-2"></i> Settings</a>
                <hr>
                <a href="signin?logout=true" class="nav-link text-danger"><i class="bi bi-box-arrow-right me-2"></i> Logout</a>
            </div>
        </nav>
        <main class="content-wrapper">
            <div class="container-fluid" style="max-width: 800px;">
                <h1 class="h3 mb-4 fw-bold">Settings</h1>

                <?php if ($message): ?>
                    <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show" role="alert">
                        <?php echo $message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>

                <!-- Profile Settings -->
                <div class="settings-card">
                    <div class="card-header">
                        <i class="bi bi-person-circle me-2"></i> Profile Information
                    </div>
                    <div class="card-body">
                        <form method="POST">
                            <div class="mb-3">
                                <label class="form-label">Email Address</label>
                                <input type="text" class="form-control" value="<?php echo htmlspecialchars($user_info['email']); ?>" disabled>
                                <small class="text-muted">Email address cannot be changed for security reasons.</small>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Full Name</label>
                                <input type="text" name="full_name" class="form-control" value="<?php echo htmlspecialchars($user_info['name']); ?>" required>
                            </div>
                            <button type="submit" name="update_profile" class="btn btn-primary">Update Profile</button>
                        </form>
                    </div>
                </div>

                <!-- Password Settings -->
                <div class="settings-card">
                    <div class="card-header">
                        <i class="bi bi-shield-lock me-2"></i> Change Password
                    </div>
                    <div class="card-body">
                        <form method="POST">
                            <div class="mb-3">
                                <label class="form-label">Current Password</label>
                                <input type="password" name="current_password" class="form-control" required>
                            </div>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">New Password</label>
                                    <input type="password" name="new_password" class="form-control" required minlength="6">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Confirm New Password</label>
                                    <input type="password" name="confirm_password" class="form-control" required>
                                </div>
                            </div>
                            <button type="submit" name="update_password" class="btn btn-primary">Change Password</button>
                        </form>
                    </div>
                </div>
            </div>
        </main>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const mobileMenuToggle = document.getElementById('mobileMenuToggle');
            const sidebarNav = document.getElementById('sidebarNav');
            const overlay = document.getElementById('overlay');

            if (mobileMenuToggle && sidebarNav && overlay) {
                mobileMenuToggle.addEventListener('click', () => {
                    sidebarNav.classList.toggle('show');
                    overlay.classList.toggle('show');
                });

                overlay.addEventListener('click', () => {
                    sidebarNav.classList.remove('show');
                    overlay.classList.remove('show');
                });

                document.querySelectorAll('.nav-link').forEach(link => {
                    link.addEventListener('click', () => {
                        if (window.innerWidth <= 768) {
                            sidebarNav.classList.remove('show');
                            overlay.classList.remove('show');
                        }
                    });
                });
            }
        });
    </script>
</body>
</html>