<?php
require_once '../config/config.php';
requireLogin('candidate');

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

$candidate_id = $_SESSION['user_id'];

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

// Get candidate details
$stmt = $db->prepare("SELECT * FROM candidates WHERE id = ?");
$stmt->execute([$candidate_id]);
$candidate = $stmt->fetch();

if (!$candidate) {
    redirect('../auth/logout.php');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $first_name = sanitize($_POST['first_name']);
    $last_name = sanitize($_POST['last_name']);
    $email = sanitize($_POST['email']);
    $phone = sanitize($_POST['phone']);
    $address = sanitize($_POST['address']);
    $date_of_birth = $_POST['date_of_birth'];
    $gender = $_POST['gender'];
    $password = $_POST['password'];
    
    if (empty($first_name) || empty($last_name) || empty($email)) {
        $error = 'First name, last name, and email are required.';
    } else {
        // Check if email is already used by someone else
        $check_tables = [
            ['table' => 'candidates', 'email_field' => 'email'],
            ['table' => 'company_users', 'email_field' => 'email'],
            ['table' => 'admins', 'email_field' => 'email']
        ];
        
        $email_exists = false;
        foreach ($check_tables as $check) {
            $stmt = $db->prepare("SELECT id FROM {$check['table']} WHERE {$check['email_field']} = ? AND id != ?");
            $params = [$email];
            if ($check['table'] === 'candidates') {
                $params[] = $candidate_id;
            } else {
                $params[] = 0; // For other tables, just check if email exists
            }
            $stmt->execute($params);
            if ($stmt->fetch()) {
                $email_exists = true;
                break;
            }
        }
        
        if ($email_exists) {
            $error = 'Email address is already in use.';
        } else {
            try {
                // Handle profile picture upload
                $profile_picture = $candidate['profile_picture'];
                if (isset($_FILES['profile_picture']) && $_FILES['profile_picture']['error'] === UPLOAD_ERR_OK) {
                    $upload_dir = '../uploads/profiles/';
                    
                    if (!file_exists($upload_dir)) {
                        mkdir($upload_dir, 0777, true);
                    }
                    
                    $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
                    $file_type = $_FILES['profile_picture']['type'];
                    
                    if (in_array($file_type, $allowed_types)) {
                        $file_extension = pathinfo($_FILES['profile_picture']['name'], PATHINFO_EXTENSION);
                        $new_filename = uniqid() . '.' . $file_extension;
                        $upload_path = $upload_dir . $new_filename;
                        
                        if (move_uploaded_file($_FILES['profile_picture']['tmp_name'], $upload_path)) {
                            // Delete old profile picture if it exists
                            if ($profile_picture && file_exists($upload_dir . $profile_picture)) {
                                unlink($upload_dir . $profile_picture);
                            }
                            $profile_picture = $new_filename;
                        } else {
                            $error = 'Failed to upload profile picture.';
                        }
                    } else {
                        $error = 'Profile picture must be a JPEG, PNG, or GIF image.';
                    }
                }
                
                if (!$error) {
                    if (!empty($password)) {
                        // Update with new password
                        if (strlen($password) < 6) {
                            $error = 'Password must be at least 6 characters long.';
                        } else {
                            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                            $stmt = $db->prepare("
                                UPDATE candidates 
                                SET first_name = ?, last_name = ?, email = ?, phone = ?, address = ?, 
                                    date_of_birth = ?, gender = ?, profile_picture = ?, password = ?
                                WHERE id = ?
                            ");
                            $stmt->execute([
                                $first_name, $last_name, $email, $phone, $address, 
                                $date_of_birth ?: null, $gender ?: null, $profile_picture, 
                                $hashed_password, $candidate_id
                            ]);
                        }
                    } else {
                        // Update without changing password
                        $stmt = $db->prepare("
                            UPDATE candidates 
                            SET first_name = ?, last_name = ?, email = ?, phone = ?, address = ?, 
                                date_of_birth = ?, gender = ?, profile_picture = ?
                            WHERE id = ?
                        ");
                        $stmt->execute([
                            $first_name, $last_name, $email, $phone, $address, 
                            $date_of_birth ?: null, $gender ?: null, $profile_picture, $candidate_id
                        ]);
                    }
                    
                    if (!$error) {
                        $success = 'Profile updated successfully!';
                        
                        // Update session variables
                        $_SESSION['user_email'] = $email;
                        $_SESSION['first_name'] = $first_name;
                        $_SESSION['last_name'] = $last_name;
                        
                        // Refresh candidate data
                        $stmt = $db->prepare("SELECT * FROM candidates WHERE id = ?");
                        $stmt->execute([$candidate_id]);
                        $candidate = $stmt->fetch();
                    }
                }
            } catch (PDOException $e) {
                $error = 'Error updating profile. Please try again.';
            }
        }
    }
}

// Check profile completion
$profile_completion = 0;
$total_fields = 8;
$completed_fields = 0;

if (!empty($candidate['first_name'])) $completed_fields++;
if (!empty($candidate['last_name'])) $completed_fields++;
if (!empty($candidate['email'])) $completed_fields++;
if (!empty($candidate['phone'])) $completed_fields++;
if (!empty($candidate['address'])) $completed_fields++;
if (!empty($candidate['date_of_birth'])) $completed_fields++;
if (!empty($candidate['gender'])) $completed_fields++;
if (!empty($candidate['profile_picture'])) $completed_fields++;

$profile_completion = round(($completed_fields / $total_fields) * 100);

// Get resumes count
$stmt = $db->prepare("SELECT COUNT(*) as resume_count FROM resumes WHERE candidate_id = ?");
$stmt->execute([$candidate_id]);
$resume_stats = $stmt->fetch();

// Get applications count
$stmt = $db->prepare("SELECT COUNT(*) as application_count FROM job_applications WHERE candidate_id = ?");
$stmt->execute([$candidate_id]);
$application_stats = $stmt->fetch();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Profile - <?php echo SITE_NAME; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-briefcase me-2"></i><?php echo SITE_NAME; ?>
            </a>
            
            <div class="navbar-nav ms-auto">
                <span class="navbar-text me-3">
                    Welcome, <?php echo htmlspecialchars($_SESSION['first_name'] . ' ' . $_SESSION['last_name']); ?>
                </span>
                <a class="nav-link" href="../auth/logout.php">
                    <i class="fas fa-sign-out-alt me-1"></i>Logout
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <nav class="col-md-3 col-lg-2 sidebar">
                <div class="position-sticky">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="dashboard.php">
                                <i class="fas fa-tachometer-alt me-2"></i>Dashboard
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="profile.php">
                                <i class="fas fa-user me-2"></i>My Profile
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="cv-builder.php">
                                <i class="fas fa-file-alt me-2"></i>CV Builder
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="applications.php">
                                <i class="fas fa-paper-plane me-2"></i>My Applications
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="../jobs.php">
                                <i class="fas fa-search me-2"></i>Browse Jobs
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- Main Content -->
            <main class="col-md-9 col-lg-10 px-md-4">
                <div class="py-4">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h1 class="h2">
                            <i class="fas fa-user me-2"></i>My Profile
                        </h1>
                    </div>

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

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

                    <div class="row">
                        <!-- Profile Form -->
                        <div class="col-lg-8">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">
                                        <i class="fas fa-edit me-2"></i>Personal Information
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <form method="POST" enctype="multipart/form-data">
                                        <div class="row">
                                            <div class="col-md-8">
                                                <div class="row">
                                                    <div class="col-md-6 mb-3">
                                                        <label for="first_name" class="form-label">First Name *</label>
                                                        <input type="text" class="form-control" id="first_name" name="first_name" 
                                                               value="<?php echo htmlspecialchars($candidate['first_name']); ?>" required>
                                                    </div>
                                                    <div class="col-md-6 mb-3">
                                                        <label for="last_name" class="form-label">Last Name *</label>
                                                        <input type="text" class="form-control" id="last_name" name="last_name" 
                                                               value="<?php echo htmlspecialchars($candidate['last_name']); ?>" required>
                                                    </div>
                                                </div>
                                                
                                                <div class="mb-3">
                                                    <label for="email" class="form-label">Email Address *</label>
                                                    <input type="email" class="form-control" id="email" name="email" 
                                                           value="<?php echo htmlspecialchars($candidate['email']); ?>" required>
                                                </div>
                                                
                                                <div class="mb-3">
                                                    <label for="phone" class="form-label">Phone Number</label>
                                                    <input type="tel" class="form-control" id="phone" name="phone" 
                                                           value="<?php echo htmlspecialchars($candidate['phone']); ?>">
                                                </div>

                                                <div class="row">
                                                    <div class="col-md-6 mb-3">
                                                        <label for="date_of_birth" class="form-label">Date of Birth</label>
                                                        <input type="date" class="form-control" id="date_of_birth" name="date_of_birth" 
                                                               value="<?php echo $candidate['date_of_birth']; ?>" max="<?php echo date('Y-m-d', strtotime('-16 years')); ?>">
                                                    </div>
                                                    <div class="col-md-6 mb-3">
                                                        <label for="gender" class="form-label">Gender</label>
                                                        <select class="form-select" id="gender" name="gender">
                                                            <option value="">Select Gender</option>
                                                            <option value="male" <?php echo $candidate['gender'] === 'male' ? 'selected' : ''; ?>>Male</option>
                                                            <option value="female" <?php echo $candidate['gender'] === 'female' ? 'selected' : ''; ?>>Female</option>
                                                            <option value="other" <?php echo $candidate['gender'] === 'other' ? 'selected' : ''; ?>>Other</option>
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-4 text-center">
                                                <div class="mb-3">
                                                    <label class="form-label">Profile Picture</label>
                                                    <div class="mb-3">
                                                        <?php if ($candidate['profile_picture']): ?>
                                                            <img src="<?php echo UPLOAD_URL . 'profiles/' . $candidate['profile_picture']; ?>" 
                                                                 alt="Profile Picture" class="profile-picture img-fluid">
                                                        <?php else: ?>
                                                            <div class="profile-picture bg-light d-flex align-items-center justify-content-center mx-auto">
                                                                <i class="fas fa-user text-muted fa-4x"></i>
                                                            </div>
                                                        <?php endif; ?>
                                                    </div>
                                                    <input type="file" class="form-control" name="profile_picture" accept="image/*">
                                                    <div class="form-text">Upload your photo (optional)</div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="address" class="form-label">Address</label>
                                            <textarea class="form-control" id="address" name="address" rows="3" 
                                                      placeholder="Your current address"><?php echo htmlspecialchars($candidate['address']); ?></textarea>
                                        </div>
                                        
                                        <div class="mb-4">
                                            <label for="password" class="form-label">New Password</label>
                                            <input type="password" class="form-control" id="password" name="password" 
                                                   placeholder="Leave blank to keep current password">
                                            <div class="form-text">Minimum 6 characters</div>
                                        </div>
                                        
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-save me-1"></i>Update Profile
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>

                        <!-- Profile Stats & Quick Actions -->
                        <div class="col-lg-4">
                            <!-- Profile Completion -->
                            <div class="card mb-4">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">
                                        <i class="fas fa-chart-pie me-2"></i>Profile Completion
                                    </h5>
                                </div>
                                <div class="card-body text-center">
                                    <div class="mb-3">
                                        <div class="progress" style="height: 20px;">
                                            <div class="progress-bar" role="progressbar" 
                                                 style="width: <?php echo $profile_completion; ?>%" 
                                                 aria-valuenow="<?php echo $profile_completion; ?>" 
                                                 aria-valuemin="0" aria-valuemax="100">
                                                <?php echo $profile_completion; ?>%
                                            </div>
                                        </div>
                                    </div>
                                    <p class="text-muted">
                                        <?php echo $completed_fields; ?> of <?php echo $total_fields; ?> fields completed
                                    </p>
                                    <?php if ($profile_completion < 100): ?>
                                        <p class="text-warning small">
                                            <i class="fas fa-exclamation-triangle me-1"></i>
                                            Complete your profile to increase visibility to employers
                                        </p>
                                    <?php else: ?>
                                        <p class="text-success small">
                                            <i class="fas fa-check-circle me-1"></i>
                                            Your profile is complete!
                                        </p>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Quick Stats -->
                            <div class="card mb-4">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">
                                        <i class="fas fa-chart-bar me-2"></i>Quick Stats
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                        <span><i class="fas fa-file-alt me-2 text-primary"></i>Resumes</span>
                                        <span class="badge bg-primary"><?php echo $resume_stats['resume_count']; ?></span>
                                    </div>
                                    <div class="d-flex justify-content-between align-items-center">
                                        <span><i class="fas fa-paper-plane me-2 text-success"></i>Applications</span>
                                        <span class="badge bg-success"><?php echo $application_stats['application_count']; ?></span>
                                    </div>
                                </div>
                            </div>

                            <!-- Quick Actions -->
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">
                                        <i class="fas fa-bolt me-2"></i>Quick Actions
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="d-grid gap-2">
                                        <a href="cv-builder.php" class="btn btn-outline-primary">
                                            <i class="fas fa-file-alt me-2"></i>Build/Edit CV
                                        </a>
                                        <a href="../jobs.php" class="btn btn-outline-success">
                                            <i class="fas fa-search me-2"></i>Browse Jobs
                                        </a>
                                        <a href="applications.php" class="btn btn-outline-info">
                                            <i class="fas fa-paper-plane me-2"></i>View Applications
                                        </a>
                                        <a href="dashboard.php" class="btn btn-outline-secondary">
                                            <i class="fas fa-tachometer-alt me-2"></i>Back to Dashboard
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>