<?php
session_start();
require_once 'includes/auth_check.php';

$page = 'profile';
$database = new Database();
$db = $database->getConnection();

$success_message = '';
$error_message = '';
// Set a default active tab
$active_tab = 'personal';

// --- Handle Profile Information Update ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    $active_tab = 'personal'; // Keep the personal tab active
    
    $first_name = trim($_POST['first_name'] ?? '');
    $last_name = trim($_POST['last_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $date_of_birth = trim($_POST['date_of_birth'] ?? '');
    $gender = trim($_POST['gender'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $country = trim($_POST['country'] ?? '');
    $employment_status = trim($_POST['employment_status'] ?? '');
    $income_source = trim($_POST['income_source'] ?? '');
    
    if (empty($first_name) || empty($last_name) || empty($email)) {
        $error_message = "First name, last name, and email are required fields.";
    } else {
        try {
            $stmt = $db->prepare("UPDATE users SET first_name = ?, last_name = ?, email = ?, phone = ?, date_of_birth = ?, gender = ?, address = ?, country = ?, employment_status = ?, income_source = ?, updated_at = NOW() WHERE id = ?");
            $stmt->execute([$first_name, $last_name, $email, $phone, $date_of_birth, $gender, $address, $country, $employment_status, $income_source, $_SESSION['user_id']]);
            $success_message = "Your profile has been updated successfully.";
        } catch (PDOException $e) {
            $error_message = "An error occurred while updating your profile.";
            error_log("Profile Update Error: " . $e->getMessage());
        }
    }
}

// --- Handle Password Change ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])) {
    $active_tab = 'security'; // Set the active tab to 'security'
    $current_password = $_POST['current_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    
    if (empty($current_password) || empty($new_password) || empty($confirm_password)) {
        $error_message = "All password fields are required.";
    } elseif ($new_password !== $confirm_password) {
        $error_message = "New password and confirmation do not match.";
    } else {
        try {
            $stmt = $db->prepare("SELECT password FROM users WHERE id = ?");
            $stmt->execute([$_SESSION['user_id']]);
            $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$user_data || !password_verify($current_password, $user_data['password'])) {
                $error_message = "Your current password is not correct.";
            } else {
                $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                $stmt = $db->prepare("UPDATE users SET password = ? WHERE id = ?");
                $stmt->execute([$hashed_password, $_SESSION['user_id']]);
                $success_message = "Your password has been updated successfully.";
            }
        } catch (PDOException $e) {
            $error_message = "An error occurred while updating your password.";
            error_log("Password Update Error: " . $e->getMessage());
        }
    }
}

// --- Handle Profile Picture Upload ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_picture'])) {
    $active_tab = 'security'; // Keep the security tab active
    $root_path = dirname(__DIR__); 
    $upload_dir = $root_path . '/uploads/profiles/';

    if (!isset($_FILES['profile_picture']) || $_FILES['profile_picture']['error'] !== UPLOAD_ERR_OK) {
        $error_message = "No file was uploaded or an upload error occurred.";
    } elseif (!file_exists($upload_dir) || !is_dir($upload_dir)) {
        $error_message = "Configuration Error: The upload directory does not exist.";
    } elseif (!is_writable($upload_dir)) {
        $error_message = "Configuration Error: The directory '{$upload_dir}' is not writable. Please check permissions.";
    } else {
        $file = $_FILES['profile_picture'];
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
        $file_type = mime_content_type($file['tmp_name']);
        if (!in_array($file_type, $allowed_types)) {
            $error_message = "Invalid file type. Only JPG, PNG, and GIF are allowed.";
        } elseif ($file['size'] > 5000000) {
            $error_message = "File is too large. Maximum size is 5MB.";
        } else {
            $file_extension = pathinfo($file['name'], PATHINFO_EXTENSION);
            $new_filename = 'profile_' . $_SESSION['user_id'] . '_' . time() . '.' . $file_extension;
            $upload_path = $upload_dir . $new_filename;
            if (move_uploaded_file($file['tmp_name'], $upload_path)) {
                if (!empty($user['profile_picture']) && file_exists($upload_dir . $user['profile_picture'])) {
                    @unlink($upload_dir . $user['profile_picture']);
                }
                $stmt = $db->prepare("UPDATE users SET profile_picture = ? WHERE id = ?");
                $stmt->execute([$new_filename, $_SESSION['user_id']]);
                $success_message = "Your profile picture has been updated successfully.";
            } else {
                $error_message = "An unknown error occurred while moving the file.";
            }
        }
    }
}

// Get the latest user data to display
$stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
/* Profile Page Styles */
:root {
    --primary-color: #4f46e5; --primary-light: #eef2ff; --primary-dark: #4338ca;
    --gray-color: #64748b; --border-color: #e2e8f0;
}
.main-content { background-color: #f8fafc; }
.profile-card { border: 1px solid var(--border-color); border-radius: 1rem; box-shadow: 0 1px 3px 0 rgba(0,0,0,0.05); background-color: white; overflow: hidden; }
.profile-header { background: linear-gradient(135deg, #4338ca, #6366F1); color: white; padding: 2rem; text-align: center; }
.profile-picture-container { position: relative; width: 120px; height: 120px; margin: 0 auto 1rem; }
.profile-picture, .profile-picture-initial { width: 100%; height: 100%; border-radius: 50%; object-fit: cover; border: 4px solid white; box-shadow: 0 4px 12px rgba(0,0,0,0.15); background-color: #f8fafc; }
.profile-picture-initial { display: flex; align-items: center; justify-content: center; font-size: 3rem; font-weight: 700; color: white; background: linear-gradient(135deg, #4f46e5, #818cf8); }
.profile-name { font-size: 1.5rem; font-weight: 700; margin-bottom: 0.25rem; }
.profile-email { opacity: 0.8; margin-bottom: 1rem; }

/* BOOTSTRAP NATIVE TAB STYLES */
.nav-tabs .nav-link { border: none; border-bottom: 2px solid transparent; color: var(--gray-color); font-weight: 500; }
.nav-tabs .nav-link.active { color: var(--primary-color); border-color: var(--primary-color); background-color: transparent; }
.tab-content { padding: 2rem; }

.profile-section-title { font-size: 1.25rem; font-weight: 600; margin-bottom: 1.5rem; display: flex; align-items: center; }
.profile-section-title i { margin-right: 0.75rem; color: var(--primary-color); font-size: 1.5rem; }
.profile-footer { padding: 1.5rem 2rem; border-top: 1px solid var(--border-color); background-color: #f8fafc; display: flex; justify-content: flex-end; }
.btn-save { background-color: var(--primary-color); color: white; border: none; padding: 0.75rem 2rem; font-weight: 500; border-radius: 0.5rem; transition: all 0.2s ease; }
.btn-save:hover { background-color: var(--primary-dark); transform: translateY(-2px); box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
</style>

<div class="main-content">
    <div class="container py-4">
        <?php if (!empty($success_message)): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert"><?php echo $success_message; ?><button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>
        <?php endif; ?>
        <?php if (!empty($error_message)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert"><?php echo $error_message; ?><button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>
        <?php endif; ?>
        
        <div class="profile-card mb-4">
            <div class="profile-header">
                <div class="profile-picture-container">
                    <?php if (!empty($user['profile_picture'])): ?>
                        <img src="<?php echo BASE_URL . 'uploads/profiles/' . htmlspecialchars($user['profile_picture']); ?>" alt="Profile" class="profile-picture" onerror="this.onerror=null; this.src='<?php echo BASE_URL; ?>assets/images/default-avatar.png';">
                    <?php else: ?>
                        <div class="profile-picture-initial"><?php echo strtoupper(substr($user['first_name'] ?? 'U', 0, 1)); ?></div>
                    <?php endif; ?>
                </div>
                <h2 class="profile-name"><?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?></h2>
                <p class="profile-email"><?php echo htmlspecialchars($user['email']); ?></p>
            </div>
            
            <!-- Nav tabs -->
            <ul class="nav nav-tabs px-3" id="profileTab" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link <?php echo ($active_tab == 'personal') ? 'active' : ''; ?>" data-bs-toggle="tab" data-bs-target="#personal-tab-pane" type="button" role="tab">Personal Information</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link <?php echo ($active_tab == 'security') ? 'active' : ''; ?>" data-bs-toggle="tab" data-bs-target="#security-tab-pane" type="button" role="tab">Security</button>
                </li>
            </ul>

            <!-- Tab panes -->
            <div class="tab-content" id="profileTabContent">
                <!-- Personal Information Tab -->
                <div class="tab-pane fade <?php echo ($active_tab == 'personal') ? 'show active' : ''; ?>" id="personal-tab-pane" role="tabpanel">
                    <form method="post" action="profile.php">
                        <div class="profile-section">
                            <h3 class="profile-section-title"><i class='bx bx-user-circle'></i> Personal Details</h3>
                            <div class="row g-3">
                                <div class="col-md-6"><div class="form-floating"><input type="text" class="form-control" name="first_name" placeholder="First Name" value="<?php echo htmlspecialchars($user['first_name']); ?>" required><label>First Name</label></div></div>
                                <div class="col-md-6"><div class="form-floating"><input type="text" class="form-control" name="last_name" placeholder="Last Name" value="<?php echo htmlspecialchars($user['last_name']); ?>" required><label>Last Name</label></div></div>
                                <div class="col-md-6"><div class="form-floating"><input type="email" class="form-control" name="email" placeholder="Email" value="<?php echo htmlspecialchars($user['email']); ?>" required><label>Email Address</label></div></div>
                                <div class="col-md-6"><div class="form-floating"><input type="tel" class="form-control" name="phone" placeholder="Phone" value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>"><label>Phone Number</label></div></div>
                                <div class="col-md-6"><div class="form-floating"><input type="text" class="form-control" value="<?php echo htmlspecialchars($user['username']); ?>" readonly disabled><label>Username (cannot be changed)</label></div></div>
                                <div class="col-md-6"><div class="form-floating"><input type="date" class="form-control" name="date_of_birth" placeholder="Date of Birth" value="<?php echo htmlspecialchars($user['date_of_birth'] ?? ''); ?>"><label>Date of Birth</label></div></div>
                                <div class="col-md-6"><div class="form-floating"><select class="form-select" name="gender"><option value="">Select Gender</option><option value="Male" <?php echo ($user['gender'] == 'Male') ? 'selected' : ''; ?>>Male</option><option value="Female" <?php echo ($user['gender'] == 'Female') ? 'selected' : ''; ?>>Female</option><option value="Other" <?php echo ($user['gender'] == 'Other') ? 'selected' : ''; ?>>Other</option></select><label>Gender</label></div></div>
                            </div>
                        </div>
                        <div class="profile-section">
                            <h3 class="profile-section-title"><i class='bx bx-map'></i> Address & Employment</h3>
                            <div class="row g-3">
                                <div class="col-12"><div class="form-floating"><input type="text" class="form-control" name="address" placeholder="Address" value="<?php echo htmlspecialchars($user['address'] ?? ''); ?>"><label>Full Address</label></div></div>
                                <div class="col-md-6"><div class="form-floating"><input type="text" class="form-control" name="country" placeholder="Country" value="<?php echo htmlspecialchars($user['country'] ?? ''); ?>"><label>Country</label></div></div>
                                <div class="col-md-6"><div class="form-floating"><select class="form-select" name="employment_status"><option value="">Select Status</option><option value="Employed" <?php echo ($user['employment_status'] == 'Employed') ? 'selected' : ''; ?>>Employed</option><option value="Self-Employed" <?php echo ($user['employment_status'] == 'Self-Employed') ? 'selected' : ''; ?>>Self-Employed</option><option value="Unemployed" <?php echo ($user['employment_status'] == 'Unemployed') ? 'selected' : ''; ?>>Unemployed</option><option value="Student" <?php echo ($user['employment_status'] == 'Student') ? 'selected' : ''; ?>>Student</option></select><label>Employment Status</label></div></div>
                                <div class="col-md-6"><div class="form-floating"><select class="form-select" name="income_source"><option value="">Select Source</option><option value="Salary" <?php echo ($user['income_source'] == 'Salary') ? 'selected' : ''; ?>>Salary</option><option value="Business" <?php echo ($user['income_source'] == 'Business') ? 'selected' : ''; ?>>Business</option><option value="Investments" <?php echo ($user['income_source'] == 'Investments') ? 'selected' : ''; ?>>Investments</option><option value="Other" <?php echo ($user['income_source'] == 'Other') ? 'selected' : ''; ?>>Other</option></select><label>Primary Income Source</label></div></div>
                            </div>
                        </div>
                        <div class="profile-footer">
                            <button type="submit" name="update_profile" value="1" class="btn btn-save">Save Changes</button>
                        </div>
                    </form>
                </div>
                
                <!-- Security Tab -->
                <div class="tab-pane fade <?php echo ($active_tab == 'security') ? 'show active' : ''; ?>" id="security-tab-pane" role="tabpanel">
                    <!-- Change Password Form -->
                    <div class="profile-section">
                        <h3 class="profile-section-title"><i class='bx bx-lock-alt'></i> Change Password</h3>
                        <form method="post" action="profile.php">
                            <div class="row g-3">
                                <div class="col-md-6"><div class="form-floating"><input type="password" class="form-control" name="current_password" placeholder="Current Password" required><label>Current Password</label></div></div>
                                <div class="col-md-6"></div>
                                <div class="col-md-6"><div class="form-floating"><input type="password" class="form-control" name="new_password" placeholder="New Password" required><label>New Password</label></div></div>
                                <div class="col-md-6"><div class="form-floating"><input type="password" class="form-control" name="confirm_password" placeholder="Confirm New Password" required><label>Confirm New Password</label></div></div>
                            </div>
                            <div class="mt-4"><button type="submit" name="change_password" value="1" class="btn btn-primary">Update Password</button></div>
                        </form>
                    </div>
                    
                    <!-- Change Profile Picture Form -->
                    <div class="profile-section mt-5">
                        <h3 class="profile-section-title"><i class='bx bx-image-add'></i> Change Profile Picture</h3>
                        <form method="post" enctype="multipart/form-data" action="profile.php">
                            <div class="mb-3">
                                <label for="profile-picture-input" class="form-label">Select a new picture (Max 5MB)</label>
                                <input type="file" class="form-control" name="profile_picture" id="profile-picture-input" accept="image/jpeg, image/png, image/gif" required>
                            </div>
                            <button type="submit" name="upload_picture" value="1" class="btn btn-primary">Upload Picture</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>

<!-- NO CUSTOM JAVASCRIPT IS NEEDED FOR THE TABS TO WORK -->
<!-- Bootstrap's own JS, loaded in your footer, will handle the tab functionality -->
