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

$page_title = 'My Profile';

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

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

// Handle profile update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $phone = trim($_POST['phone']);
    $address = trim($_POST['address']);
    $city = trim($_POST['city']);
    $state = trim($_POST['state']);
    
    // Validate
    if (empty($first_name)) $errors[] = "First name is required";
    if (empty($last_name)) $errors[] = "Last name is required";
    if (empty($phone) || !Security::validatePhone($phone)) {
        $errors[] = "Valid phone number is required";
    }
    
    // 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 ($profile_photo && file_exists($profile_photo)) {
                        unlink($profile_photo);
                    }
                    $profile_photo = 'uploads/profiles/' . $filename;
                }
            } else {
                $errors[] = "Invalid profile photo";
            }
        }
    }
    
    if (empty($errors)) {
        $sql = "UPDATE users SET 
                first_name = ?, last_name = ?, phone = ?, address = ?,
                city = ?, state = ?, profile_photo = ?, updated_at = NOW()
                WHERE id = ?";
        
        $db->execute($sql, [
            $first_name, $last_name, $phone, $address,
            $city, $state, $profile_photo, $current_user['id']
        ]);
        
        $_SESSION['success'] = "Profile updated successfully!";
        header('Location: profile.php');
        exit;
    }
}

// Handle password change
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])) {
    $current_password = $_POST['current_password'];
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];
    
    // Verify current password
    if (!Security::verifyPassword($current_password, $current_user['password_hash'])) {
        $errors[] = "Current password is incorrect";
    }
    
    if (strlen($new_password) < 8) {
        $errors[] = "New password must be at least 8 characters";
    }
    
    if ($new_password !== $confirm_password) {
        $errors[] = "New passwords do not match";
    }
    
    if (empty($errors)) {
        $new_hash = Security::hashPassword($new_password);
        $sql = "UPDATE users SET password_hash = ?, updated_at = NOW() WHERE id = ?";
        $db->execute($sql, [$new_hash, $current_user['id']]);
        
        $_SESSION['success'] = "Password changed successfully!";
        header('Location: profile.php');
        exit;
    }
}

// Refresh user data
$current_user = $auth->getCurrentUser();

include 'includes/header.php';
?>

<div class="page-header">
    <h1>My Profile</h1>
    <p class="text-muted mb-0">Manage your personal information and settings</p>
</div>

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

<?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; ?>

<div class="row">
    <!-- Profile Overview -->
    <div class="col-lg-4">
        <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="rounded-circle mx-auto mb-3 d-flex align-items-center justify-content-center"
                     style="width: 150px; height: 150px; background: var(--primary); color: white; font-size: 4rem; font-weight: bold;">
                    <?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>
                
                <?php
                $status_badge = [
                    'active' => 'success',
                    'pending' => 'warning',
                    'suspended' => 'danger'
                ][$current_user['status']] ?? 'secondary';
                ?>
                <span class="badge bg-<?php echo $status_badge; ?> mb-3">
                    <?php echo ucfirst($current_user['status']); ?>
                </span>
                
                <hr>
                
                <div class="text-start">
                    <div class="mb-2">
                        <i class="fas fa-envelope text-primary me-2"></i>
                        <?php echo $current_user['email_verified'] ? 
                            '<span class="text-success"><i class="fas fa-check-circle"></i> Email Verified</span>' :
                            '<span class="text-warning"><i class="fas fa-exclamation-circle"></i> Email Not Verified</span>';
                        ?>
                    </div>
                    <div class="mb-2">
                        <i class="fas fa-phone text-primary me-2"></i>
                        <?php echo $current_user['phone_verified'] ? 
                            '<span class="text-success"><i class="fas fa-check-circle"></i> Phone Verified</span>' :
                            '<span class="text-warning"><i class="fas fa-exclamation-circle"></i> Phone Not Verified</span>';
                        ?>
                    </div>
                    <div class="mb-2">
                        <i class="fas fa-calendar text-primary me-2"></i>
                        Member since <?php echo date('F Y', strtotime($current_user['created_at'])); ?>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Quick Actions -->
        <div class="card">
            <div class="card-header">
                <h6 class="mb-0">Quick Actions</h6>
            </div>
            <div class="card-body">
                <div class="d-grid gap-2">
                    <a href="complete-profile.php" class="btn btn-outline-primary">
                        <i class="fas fa-user-edit"></i> Update Profile Details
                    </a>
                    <a href="documents.php" class="btn btn-outline-info">
                        <i class="fas fa-folder"></i> My Documents
                    </a>
                    <a href="verification-status.php" class="btn btn-outline-success">
                        <i class="fas fa-check-circle"></i> Verification Status
                    </a>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Profile Forms -->
    <div class="col-lg-8">
        <!-- Basic Information -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-user"></i> Basic Information</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="mb-3">
                        <label class="form-label">Email Address</label>
                        <input type="email" class="form-control" disabled
                               value="<?php echo htmlspecialchars($current_user['email']); ?>">
                        <small class="text-muted">Contact support to change your email</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Phone Number <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 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">JPG, PNG (Max 5MB)</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 mb-4">
            <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</label>
                        <input type="password" name="current_password" class="form-control" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">New Password</label>
                        <input type="password" name="new_password" class="form-control" required minlength="8">
                        <small class="text-muted">At least 8 characters</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Confirm New Password</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>
        
        <!-- Account Settings -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-cog"></i> Account Settings</h5>
            </div>
            <div class="card-body">
                <div class="form-check form-switch mb-3">
                    <input class="form-check-input" type="checkbox" id="emailNotif" checked>
                    <label class="form-check-label" for="emailNotif">
                        Email Notifications
                    </label>
                </div>
                
                <div class="form-check form-switch mb-3">
                    <input class="form-check-input" type="checkbox" id="smsNotif">
                    <label class="form-check-label" for="smsNotif">
                        SMS Notifications
                    </label>
                </div>
                
                <div class="form-check form-switch mb-3">
                    <input class="form-check-input" type="checkbox" id="marketingEmails">
                    <label class="form-check-label" for="marketingEmails">
                        Marketing Emails
                    </label>
                </div>
                
                <hr>
                
                <button class="btn btn-outline-danger" data-bs-toggle="modal" data-bs-target="#deleteAccountModal">
                    <i class="fas fa-trash-alt"></i> Delete Account
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Delete Account Modal -->
<div class="modal fade" id="deleteAccountModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">Delete Account</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i>
                    <strong>Warning!</strong> This action cannot be undone.
                </div>
                
                <p>Deleting your account will:</p>
                <ul>
                    <li>Permanently delete all your data</li>
                    <li>Cancel all pending applications</li>
                    <li>Remove all uploaded documents</li>
                    <li>Disable access to your account immediately</li>
                </ul>
                
                <p class="mb-0">
                    If you're sure, type <strong>DELETE</strong> below:
                </p>
                <input type="text" class="form-control mt-2" id="deleteConfirm" placeholder="Type DELETE">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="confirmDelete" disabled>
                    Delete My Account
                </button>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Enable delete button only when typed correctly
    $('#deleteConfirm').on('input', function() {
        const val = $(this).val();
        $('#confirmDelete').prop('disabled', val !== 'DELETE');
    });
    
    // Handle account deletion
    $('#confirmDelete').click(function() {
        Swal.fire({
            title: 'Final Confirmation',
            text: 'Are you absolutely sure? This cannot be undone!',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            confirmButtonText: 'Yes, Delete Forever'
        }).then((result) => {
            if (result.isConfirmed) {
                // Implement account deletion
                Swal.fire('Deleted!', 'Your account has been deleted.', 'success');
            }
        });
    });
});
</script>

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