<?php
define('ROVO_APP', true);
require_once '../config.php';
require_once '../Auth.php';

$page_title = 'My Profile';

if (!$auth->isLoggedIn()) {
    header('Location: ../login.php');
    exit;
}

$current_user = $auth->getCurrentUser();
$errors = [];
$success = '';

// Handle profile update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    if (!Security::validateCSRFToken($_POST['csrf_token'])) {
        $errors[] = 'Invalid CSRF token';
    } else {
        $first_name = trim($_POST['first_name']);
        $last_name = trim($_POST['last_name']);
        $email = trim($_POST['email']);
        $phone = trim($_POST['phone']);
        $address = trim($_POST['address']);
        $city = trim($_POST['city']);
        $state = trim($_POST['state']);
        
        if (empty($first_name)) $errors[] = "First name is required";
        if (empty($last_name)) $errors[] = "Last name is required";
        if (empty($email) || !Security::validateEmail($email)) $errors[] = "Valid email is required";
        if (empty($phone) || !Security::validatePhone($phone)) $errors[] = "Valid phone is required";
        
        // Check if email is already taken by another user
        if ($email !== $current_user['email']) {
            $email_check = $db->fetchOne("SELECT id FROM users WHERE email = ? AND id != ?", [$email, $current_user['id']]);
            if ($email_check) {
                $errors[] = "Email is already taken";
            }
        }
        
        // Handle profile photo upload
        $profile_photo = $current_user['profile_photo'];
        
        if (!empty($_FILES['profile_photo']['name'])) {
            $file = $_FILES['profile_photo'];
            if ($file['error'] === UPLOAD_ERR_OK) {
                if (in_array($file['type'], ALLOWED_IMAGE_TYPES) && $file['size'] <= MAX_FILE_SIZE) {
                    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
                    $filename = 'profile_' . $current_user['id'] . '_' . time() . '.' . $extension;
                    $upload_path = PROFILE_UPLOAD_DIR . '/' . $filename;
                    
                    if (move_uploaded_file($file['tmp_name'], $upload_path)) {
                        // Delete old photo
                        if ($current_user['profile_photo']) {
                            $old_file = PROFILE_UPLOAD_DIR . '/' . basename($current_user['profile_photo']);
                            if (file_exists($old_file)) unlink($old_file);
                        }
                        $profile_photo = 'uploads/profiles/' . $filename;
                    }
                } else {
                    $errors[] = "Invalid image file";
                }
            }
        }
        
        if (empty($errors)) {
            try {
                $sql = "UPDATE users SET 
                        first_name = ?, last_name = ?, email = ?, phone = ?,
                        address = ?, city = ?, state = ?, profile_photo = ?,
                        updated_at = NOW()
                        WHERE id = ?";
                
                $db->execute($sql, [
                    $first_name, $last_name, $email, $phone,
                    $address, $city, $state, $profile_photo,
                    $current_user['id']
                ]);
                
                // Update session
                $_SESSION['user_name'] = $first_name . ' ' . $last_name;
                $_SESSION['user_email'] = $email;
                
                // Log activity
                $sql = "INSERT INTO activity_logs (user_id, action, entity_type, entity_id, description, ip_address, user_agent) 
                        VALUES (?, 'update_profile', 'user', ?, 'Profile updated', ?, ?)";
                $db->execute($sql, [
                    $current_user['id'],
                    $current_user['id'],
                    Security::getClientIP(),
                    $_SERVER['HTTP_USER_AGENT'] ?? ''
                ]);
                
                $success = "Profile updated successfully!";
                $current_user = $auth->getCurrentUser(); // Refresh user data
                
            } catch (Exception $e) {
                $errors[] = "Failed to update profile: " . $e->getMessage();
            }
        }
    }
}

// Handle password change
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])) {
    if (!Security::validateCSRFToken($_POST['csrf_token'])) {
        $errors[] = 'Invalid CSRF token';
    } else {
        $current_password = $_POST['current_password'];
        $new_password = $_POST['new_password'];
        $confirm_password = $_POST['confirm_password'];
        
        if (empty($current_password)) $errors[] = "Current password is required";
        if (empty($new_password)) $errors[] = "New password is required";
        if (strlen($new_password) < 8) $errors[] = "New password must be at least 8 characters";
        if ($new_password !== $confirm_password) $errors[] = "Passwords do not match";
        
        // Verify current password
        if (!Security::verifyPassword($current_password, $current_user['password_hash'])) {
            $errors[] = "Current password is incorrect";
        }
        
        if (empty($errors)) {
            try {
                $new_password_hash = Security::hashPassword($new_password);
                
                $sql = "UPDATE users SET password_hash = ?, updated_at = NOW() WHERE id = ?";
                $db->execute($sql, [$new_password_hash, $current_user['id']]);
                
                // Log activity
                $sql = "INSERT INTO activity_logs (user_id, action, entity_type, entity_id, description, ip_address, user_agent) 
                        VALUES (?, 'change_password', 'user', ?, 'Password changed', ?, ?)";
                $db->execute($sql, [
                    $current_user['id'],
                    $current_user['id'],
                    Security::getClientIP(),
                    $_SERVER['HTTP_USER_AGENT'] ?? ''
                ]);
                
                $success = "Password changed successfully!";
                
            } catch (Exception $e) {
                $errors[] = "Failed to change password: " . $e->getMessage();
            }
        }
    }
}

include 'includes/header.php';
?>

<div class="page-header">
    <h1>My Profile</h1>
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
            <li class="breadcrumb-item active">Profile</li>
        </ol>
    </nav>
</div>

<?php if (!empty($errors)): ?>
<div class="alert alert-danger alert-dismissible fade show">
    <ul class="mb-0">
        <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
        <?php endforeach; ?>
    </ul>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<?php if ($success): ?>
<div class="alert alert-success alert-dismissible fade show">
    <i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success); ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<div class="row">
    <div class="col-lg-4">
        <!-- Profile Card -->
        <div class="card mb-4">
            <div class="card-body text-center">
                <?php if ($current_user['profile_photo']): ?>
                <img src="../<?php echo htmlspecialchars($current_user['profile_photo']); ?>" 
                     alt="Profile" class="rounded-circle mb-3" 
                     style="width: 150px; height: 150px; object-fit: cover;">
                <?php else: ?>
                <div class="user-avatar mx-auto mb-3" style="width: 150px; height: 150px; font-size: 3rem;">
                    <?php echo strtoupper(substr($current_user['first_name'], 0, 1) . substr($current_user['last_name'], 0, 1)); ?>
                </div>
                <?php endif; ?>
                
                <h4><?php echo htmlspecialchars($current_user['first_name'] . ' ' . $current_user['last_name']); ?></h4>
                <p class="text-muted"><?php echo htmlspecialchars($current_user['email']); ?></p>
                
                <span class="badge" style="background: var(--primary); font-size: 1rem; padding: 8px 15px;">
                    <?php echo ucfirst(str_replace('_', ' ', $current_user['role'])); ?>
                </span>
                
                <hr class="my-4">
                
                <div class="text-start">
                    <p class="mb-2">
                        <i class="fas fa-phone text-primary"></i>
                        <strong class="ms-2">Phone:</strong>
                        <span class="float-end"><?php echo htmlspecialchars($current_user['phone']); ?></span>
                    </p>
                    <p class="mb-2">
                        <i class="fas fa-calendar text-primary"></i>
                        <strong class="ms-2">Joined:</strong>
                        <span class="float-end"><?php echo date('M d, Y', strtotime($current_user['created_at'])); ?></span>
                    </p>
                    <p class="mb-0">
                        <i class="fas fa-clock text-primary"></i>
                        <strong class="ms-2">Last Login:</strong>
                        <span class="float-end">
                            <?php echo $current_user['last_login'] ? date('M d, Y H:i', strtotime($current_user['last_login'])) : 'Never'; ?>
                        </span>
                    </p>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-lg-8">
        <!-- Edit Profile -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-user-edit"></i> Edit Profile</h5>
            </div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="csrf_token" value="<?php echo Security::generateCSRFToken(); ?>">
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">First Name <span class="text-danger">*</span></label>
                            <input type="text" name="first_name" class="form-control" required
                                   value="<?php echo htmlspecialchars($current_user['first_name']); ?>">
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Last Name <span class="text-danger">*</span></label>
                            <input type="text" name="last_name" class="form-control" required
                                   value="<?php echo htmlspecialchars($current_user['last_name']); ?>">
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Email <span class="text-danger">*</span></label>
                            <input type="email" name="email" class="form-control" required
                                   value="<?php echo htmlspecialchars($current_user['email']); ?>">
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Phone <span class="text-danger">*</span></label>
                            <input type="tel" name="phone" class="form-control" required
                                   value="<?php echo htmlspecialchars($current_user['phone']); ?>"
                                   pattern="^(\+?234|0)[789]\d{9}$">
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Address</label>
                        <input type="text" name="address" class="form-control"
                               value="<?php echo htmlspecialchars($current_user['address'] ?? ''); ?>">
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">City</label>
                            <input type="text" name="city" class="form-control"
                                   value="<?php echo htmlspecialchars($current_user['city'] ?? ''); ?>">
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">State</label>
                            <input type="text" name="state" class="form-control"
                                   value="<?php echo htmlspecialchars($current_user['state'] ?? ''); ?>">
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Profile Photo</label>
                        <input type="file" name="profile_photo" class="form-control" accept="image/*">
                        <small class="text-muted">Max size: 5MB. Formats: JPG, PNG</small>
                    </div>
                    
                    <button type="submit" name="update_profile" class="btn btn-primary">
                        <i class="fas fa-save"></i> Update Profile
                    </button>
                </form>
            </div>
        </div>
        
        <!-- Change Password -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-lock"></i> Change Password</h5>
            </div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="csrf_token" value="<?php echo Security::generateCSRFToken(); ?>">
                    
                    <div class="mb-3">
                        <label class="form-label">Current Password <span class="text-danger">*</span></label>
                        <input type="password" name="current_password" class="form-control" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">New Password <span class="text-danger">*</span></label>
                        <input type="password" name="new_password" class="form-control" required minlength="8">
                        <small class="text-muted">Minimum 8 characters</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Confirm New Password <span class="text-danger">*</span></label>
                        <input type="password" name="confirm_password" class="form-control" required>
                    </div>
                    
                    <button type="submit" name="change_password" class="btn btn-warning">
                        <i class="fas fa-key"></i> Change Password
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

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