<?php
/**
 * User Profile Page
 * Digital Marketplace
 */

require_once __DIR__ . '/../config/database.php';

require_login();

$page_title = 'My Profile';

$user_id = get_current_user_id();
$user = get_current_user_data($pdo);

$errors = [];
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid request. Please try again.';
    } else {
        $name = sanitize($_POST['name'] ?? '');
        $phone = sanitize($_POST['phone'] ?? '');
        $current_password = $_POST['current_password'] ?? '';
        $new_password = $_POST['new_password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';
        
        // Validate name
        if (empty($name)) {
            $errors[] = 'Name is required.';
        }
        
        // Update password if provided
        if (!empty($new_password)) {
            if (empty($current_password)) {
                $errors[] = 'Current password is required to change password.';
            } elseif (!password_verify($current_password, $user['password'])) {
                $errors[] = 'Current password is incorrect.';
            } elseif (strlen($new_password) < 8) {
                $errors[] = 'New password must be at least 8 characters.';
            } elseif ($new_password !== $confirm_password) {
                $errors[] = 'New passwords do not match.';
            }
        }
        
        if (empty($errors)) {
            try {
                $sql = "UPDATE users SET name = ?, phone = ?, updated_at = NOW()";
                $params = [$name, $phone];
                
                if (!empty($new_password)) {
                    $sql .= ", password = ?";
                    $params[] = password_hash($new_password, PASSWORD_BCRYPT);
                }
                
                $sql .= " WHERE id = ?";
                $params[] = $user_id;
                
                $stmt = $pdo->prepare($sql);
                $stmt->execute($params);
                
                // Update session
                $_SESSION['user_name'] = $name;
                
                $success = true;
                set_flash_message('Profile updated successfully!', 'success');
                
                // Refresh user data
                $user = get_current_user_data($pdo);
                
            } catch (PDOException $e) {
                $errors[] = 'Failed to update profile. Please try again.';
            }
        }
    }
}

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

<section class="section">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-lg-8" data-aos="fade-up">
                <div class="card">
                    <div class="card-header">
                        <h4 class="mb-0"><i class="fas fa-user me-2"></i>Edit Profile</h4>
                    </div>
                    <div class="card-body">
                        <?php if (!empty($errors)): ?>
                            <div class="alert alert-danger">
                                <?php foreach ($errors as $error): ?>
                                    <p class="mb-1"><i class="fas fa-exclamation-circle me-2"></i><?php echo $error; ?></p>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                        
                        <form method="POST" action="">
                            <?php echo csrf_field(); ?>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="name" class="form-label">Full Name <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="name" name="name" 
                                           value="<?php echo sanitize($user['name']); ?>" required>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label for="email" class="form-label">Email Address</label>
                                    <input type="email" class="form-control" id="email" 
                                           value="<?php echo sanitize($user['email']); ?>" disabled>
                                    <small class="text-muted">Email cannot be changed</small>
                                </div>
                            </div>
                            
                            <div class="mb-4">
                                <label for="phone" class="form-label">Phone Number</label>
                                <input type="tel" class="form-control" id="phone" name="phone" 
                                       value="<?php echo sanitize($user['phone'] ?? ''); ?>">
                            </div>
                            
                            <hr class="border-secondary my-4">
                            
                            <h5 class="mb-3"><i class="fas fa-lock me-2"></i>Change Password</h5>
                            <p class="text-muted small mb-3">Leave blank if you don't want to change your password</p>
                            
                            <div class="mb-3">
                                <label for="current_password" class="form-label">Current Password</label>
                                <input type="password" class="form-control" id="current_password" name="current_password">
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="new_password" class="form-label">New Password</label>
                                    <input type="password" class="form-control" id="new_password" name="new_password" 
                                           minlength="8">
                                    <small class="text-muted">Minimum 8 characters</small>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label for="confirm_password" class="form-label">Confirm New Password</label>
                                    <input type="password" class="form-control" id="confirm_password" name="confirm_password">
                                </div>
                            </div>
                            
                            <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                                <a href="<?php echo BASE_URL; ?>/account/index.php" class="btn btn-outline-light">Cancel</a>
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save me-2"></i>Save Changes
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

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