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

$page_title = 'Complete Your Profile';

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

$current_user = $auth->getCurrentUser();

// Check if profile is already completed and verified
if ($current_user['status'] === 'active') {
    $_SESSION['info'] = "Your profile is already verified!";
    header('Location: dashboard.php');
    exit;
}

$errors = [];
$step = isset($_GET['step']) ? (int)$_GET['step'] : 1;
$max_step = 5;

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!Security::validateCSRFToken($_POST['csrf_token'])) {
        $errors[] = 'Invalid CSRF token';
    } else {
        $current_step = (int)$_POST['step'];
        
        // Process each step
        switch ($current_step) {
            case 1: // Personal Information
                $date_of_birth = $_POST['date_of_birth'];
                $nationality = $_POST['nationality'] ?? 'Nigerian';
                $address = trim($_POST['address']);
                $city = trim($_POST['city']);
                $state = trim($_POST['state']);
                $state_of_origin = $_POST['state_of_origin'];
                $next_of_kin_name = trim($_POST['next_of_kin_name']);
                $next_of_kin_phone = trim($_POST['next_of_kin_phone']);
                
                if (empty($date_of_birth)) $errors[] = "Date of birth is required";
                if (empty($address)) $errors[] = "Address is required";
                if (empty($city)) $errors[] = "City is required";
                if (empty($state)) $errors[] = "State is required";
                if (empty($next_of_kin_name)) $errors[] = "Next of kin name is required";
                if (empty($next_of_kin_phone) || !Security::validatePhone($next_of_kin_phone)) {
                    $errors[] = "Valid next of kin phone is required";
                }
                
                if (empty($errors)) {
                    $sql = "UPDATE users SET 
                            address = ?, city = ?, state = ?, country = ?,
                            updated_at = NOW()
                            WHERE id = ?";
                    $db->execute($sql, [$address, $city, $state, $nationality, $current_user['id']]);
                    
                    // Store additional info in session for later steps
                    $_SESSION['profile_data'] = [
                        'date_of_birth' => $date_of_birth,
                        'state_of_origin' => $state_of_origin,
                        'next_of_kin_name' => $next_of_kin_name,
                        'next_of_kin_phone' => $next_of_kin_phone
                    ];
                    
                    header('Location: complete-profile.php?step=2');
                    exit;
                }
                break;
                
            case 2: // Identity Verification
                $bvn = trim($_POST['bvn']);
                $nin = trim($_POST['nin']);
                $id_type = $_POST['id_type'];
                $id_number = trim($_POST['id_number']);
                
                if (empty($bvn) || strlen($bvn) != 11) {
                    $errors[] = "Valid BVN (11 digits) is required";
                }
                
                if (!empty($nin) && strlen($nin) != 11) {
                    $errors[] = "NIN must be 11 digits";
                }
                
                if (empty($id_type)) $errors[] = "ID type is required";
                if (empty($id_number)) $errors[] = "ID number is required";
                
                // Handle file uploads
                $uploads = [];
                $upload_fields = ['id_front_image', 'id_back_image', 'passport_photo'];
                
                foreach ($upload_fields as $field) {
                    if (!empty($_FILES[$field]['name'])) {
                        $file = $_FILES[$field];
                        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 = $field . '_' . $current_user['id'] . '_' . time() . '.' . $extension;
                                $upload_path = DOCUMENT_UPLOAD_DIR . '/' . $filename;
                                
                                if (move_uploaded_file($file['tmp_name'], $upload_path)) {
                                    $uploads[$field] = 'uploads/documents/' . $filename;
                                }
                            } else {
                                $errors[] = "Invalid file for " . str_replace('_', ' ', $field);
                            }
                        }
                    } else {
                        $errors[] = ucfirst(str_replace('_', ' ', $field)) . " is required";
                    }
                }
                
                if (empty($errors)) {
                    $sql = "UPDATE users SET bvn = ?, nin = ? WHERE id = ?";
                    $db->execute($sql, [$bvn, $nin, $current_user['id']]);
                    
                    $_SESSION['profile_data'] = array_merge($_SESSION['profile_data'] ?? [], [
                        'id_type' => $id_type,
                        'id_number' => $id_number,
                        'id_front_image' => $uploads['id_front_image'],
                        'id_back_image' => $uploads['id_back_image'],
                        'passport_photo' => $uploads['passport_photo']
                    ]);
                    
                    header('Location: complete-profile.php?step=3');
                    exit;
                }
                break;
                
            case 3: // Employment & Income
                $employment_status = $_POST['employment_status'];
                $monthly_income = !empty($_POST['monthly_income']) ? (float)$_POST['monthly_income'] : 0;
                
                $employment_data = [
                    'employment_status' => $employment_status,
                    'monthly_income' => $monthly_income
                ];
                
                if ($employment_status === 'employed') {
                    $employment_data['company_name'] = trim($_POST['company_name']);
                    $employment_data['company_address'] = trim($_POST['company_address']);
                    $employment_data['job_title'] = trim($_POST['job_title']);
                    
                    if (empty($employment_data['company_name'])) $errors[] = "Company name is required";
                    if (empty($employment_data['job_title'])) $errors[] = "Job title is required";
                    
                    // Handle employment letter
                    if (!empty($_FILES['employment_letter']['name'])) {
                        $file = $_FILES['employment_letter'];
                        if ($file['error'] === UPLOAD_ERR_OK) {
                            $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
                            $filename = 'employment_letter_' . $current_user['id'] . '_' . time() . '.' . $extension;
                            $upload_path = DOCUMENT_UPLOAD_DIR . '/' . $filename;
                            
                            if (move_uploaded_file($file['tmp_name'], $upload_path)) {
                                $employment_data['employment_letter'] = 'uploads/documents/' . $filename;
                            }
                        }
                    }
                } elseif ($employment_status === 'self_employed' || $employment_status === 'business_owner') {
                    $employment_data['business_name'] = trim($_POST['business_name']);
                    
                    // Handle business registration
                    if (!empty($_FILES['business_registration']['name'])) {
                        $file = $_FILES['business_registration'];
                        if ($file['error'] === UPLOAD_ERR_OK) {
                            $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
                            $filename = 'business_reg_' . $current_user['id'] . '_' . time() . '.' . $extension;
                            $upload_path = DOCUMENT_UPLOAD_DIR . '/' . $filename;
                            
                            if (move_uploaded_file($file['tmp_name'], $upload_path)) {
                                $employment_data['business_registration'] = 'uploads/documents/' . $filename;
                            }
                        }
                    }
                }
                
                // Handle bank statement
                if (!empty($_FILES['bank_statement']['name'])) {
                    $file = $_FILES['bank_statement'];
                    if ($file['error'] === UPLOAD_ERR_OK) {
                        $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
                        $filename = 'bank_statement_' . $current_user['id'] . '_' . time() . '.' . $extension;
                        $upload_path = DOCUMENT_UPLOAD_DIR . '/' . $filename;
                        
                        if (move_uploaded_file($file['tmp_name'], $upload_path)) {
                            $employment_data['bank_statement'] = 'uploads/documents/' . $filename;
                        }
                    }
                } else {
                    $errors[] = "Bank statement is required";
                }
                
                if (empty($errors)) {
                    $_SESSION['profile_data'] = array_merge($_SESSION['profile_data'] ?? [], $employment_data);
                    header('Location: complete-profile.php?step=4');
                    exit;
                }
                break;
                
            case 4: // Guarantor Information
                $guarantor1_data = [
                    'guarantor1_name' => trim($_POST['guarantor1_name']),
                    'guarantor1_relationship' => $_POST['guarantor1_relationship'],
                    'guarantor1_phone' => trim($_POST['guarantor1_phone']),
                    'guarantor1_email' => trim($_POST['guarantor1_email']),
                    'guarantor1_address' => trim($_POST['guarantor1_address']),
                    'guarantor1_occupation' => trim($_POST['guarantor1_occupation']),
                    'guarantor1_income' => !empty($_POST['guarantor1_income']) ? (float)$_POST['guarantor1_income'] : 0
                ];
                
                if (empty($guarantor1_data['guarantor1_name'])) $errors[] = "Guarantor 1 name is required";
                if (empty($guarantor1_data['guarantor1_phone']) || !Security::validatePhone($guarantor1_data['guarantor1_phone'])) {
                    $errors[] = "Valid guarantor 1 phone is required";
                }
                
                // Optional Guarantor 2
                $guarantor2_data = [];
                if (!empty($_POST['guarantor2_name'])) {
                    $guarantor2_data = [
                        'guarantor2_name' => trim($_POST['guarantor2_name']),
                        'guarantor2_relationship' => $_POST['guarantor2_relationship'],
                        'guarantor2_phone' => trim($_POST['guarantor2_phone']),
                        'guarantor2_email' => trim($_POST['guarantor2_email']),
                        'guarantor2_address' => trim($_POST['guarantor2_address']),
                        'guarantor2_occupation' => trim($_POST['guarantor2_occupation']),
                        'guarantor2_income' => !empty($_POST['guarantor2_income']) ? (float)$_POST['guarantor2_income'] : 0
                    ];
                }
                
                // Handle guarantor form upload
                if (!empty($_FILES['guarantor_form']['name'])) {
                    $file = $_FILES['guarantor_form'];
                    if ($file['error'] === UPLOAD_ERR_OK) {
                        $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
                        $filename = 'guarantor_form_' . $current_user['id'] . '_' . time() . '.' . $extension;
                        $upload_path = DOCUMENT_UPLOAD_DIR . '/' . $filename;
                        
                        if (move_uploaded_file($file['tmp_name'], $upload_path)) {
                            $guarantor1_data['guarantor_form'] = 'uploads/documents/' . $filename;
                        }
                    }
                }
                
                if (empty($errors)) {
                    $_SESSION['profile_data'] = array_merge($_SESSION['profile_data'] ?? [], $guarantor1_data, $guarantor2_data);
                    header('Location: complete-profile.php?step=5');
                    exit;
                }
                break;
                
            case 5: // Review & Submit
                if (!isset($_POST['terms_accepted']) || !isset($_POST['bvn_consent']) || !isset($_POST['data_consent'])) {
                    $errors[] = "You must accept all terms and consents";
                }
                
                if (empty($errors)) {
                    try {
                        $db->beginTransaction();
                        
                        // Create a complete profile record (store in a JSON field or separate table)
                        $profile_data = $_SESSION['profile_data'] ?? [];
                        
                        // Update user status to pending verification
                        $sql = "UPDATE users SET status = 'pending', updated_at = NOW() WHERE id = ?";
                        $db->execute($sql, [$current_user['id']]);
                        
                        // Create a profile verification record
                        $sql = "INSERT INTO user_profile_data (
                                user_id, date_of_birth, state_of_origin, next_of_kin_name, 
                                next_of_kin_phone, id_type, id_number, id_front_image, 
                                id_back_image, passport_photo, employment_status, company_name,
                                company_address, job_title, monthly_income, employment_letter,
                                business_name, business_registration, bank_statement,
                                guarantor1_name, guarantor1_relationship, guarantor1_phone,
                                guarantor1_email, guarantor1_address, guarantor1_occupation,
                                guarantor1_income, guarantor2_name, guarantor2_relationship,
                                guarantor2_phone, guarantor2_email, guarantor2_address,
                                guarantor2_occupation, guarantor2_income, guarantor_form,
                                verification_status
                            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')";
                        
                        $db->execute($sql, [
                            $current_user['id'],
                            $profile_data['date_of_birth'] ?? null,
                            $profile_data['state_of_origin'] ?? null,
                            $profile_data['next_of_kin_name'] ?? null,
                            $profile_data['next_of_kin_phone'] ?? null,
                            $profile_data['id_type'] ?? null,
                            $profile_data['id_number'] ?? null,
                            $profile_data['id_front_image'] ?? null,
                            $profile_data['id_back_image'] ?? null,
                            $profile_data['passport_photo'] ?? null,
                            $profile_data['employment_status'] ?? null,
                            $profile_data['company_name'] ?? null,
                            $profile_data['company_address'] ?? null,
                            $profile_data['job_title'] ?? null,
                            $profile_data['monthly_income'] ?? 0,
                            $profile_data['employment_letter'] ?? null,
                            $profile_data['business_name'] ?? null,
                            $profile_data['business_registration'] ?? null,
                            $profile_data['bank_statement'] ?? null,
                            $profile_data['guarantor1_name'] ?? null,
                            $profile_data['guarantor1_relationship'] ?? null,
                            $profile_data['guarantor1_phone'] ?? null,
                            $profile_data['guarantor1_email'] ?? null,
                            $profile_data['guarantor1_address'] ?? null,
                            $profile_data['guarantor1_occupation'] ?? null,
                            $profile_data['guarantor1_income'] ?? 0,
                            $profile_data['guarantor2_name'] ?? null,
                            $profile_data['guarantor2_relationship'] ?? null,
                            $profile_data['guarantor2_phone'] ?? null,
                            $profile_data['guarantor2_email'] ?? null,
                            $profile_data['guarantor2_address'] ?? null,
                            $profile_data['guarantor2_occupation'] ?? null,
                            $profile_data['guarantor2_income'] ?? 0,
                            $profile_data['guarantor_form'] ?? null
                        ]);
                        
                        // Create notification for admin
                        $sql = "INSERT INTO notifications (user_id, type, title, message) 
                                VALUES (1, 'info', 'New Profile Verification', 'User {$current_user['first_name']} {$current_user['last_name']} submitted profile for verification')";
                        $db->execute($sql);
                        
                        // Log activity
                        $sql = "INSERT INTO activity_logs (user_id, action, entity_type, entity_id, description, ip_address, user_agent) 
                                VALUES (?, 'profile_submit', 'user', ?, 'Profile submitted for verification', ?, ?)";
                        $db->execute($sql, [
                            $current_user['id'],
                            $current_user['id'],
                            Security::getClientIP(),
                            $_SERVER['HTTP_USER_AGENT'] ?? ''
                        ]);
                        
                        $db->commit();
                        
                        // Clear session data
                        unset($_SESSION['profile_data']);
                        
                        $_SESSION['success'] = "Profile submitted successfully! Awaiting verification.";
                        header('Location: verification-status.php');
                        exit;
                        
                    } catch (Exception $e) {
                        $db->rollBack();
                        $errors[] = "Failed to submit profile: " . $e->getMessage();
                    }
                }
                break;
        }
    }
}

// Get saved data from session
$saved_data = $_SESSION['profile_data'] ?? [];

// Get Nigerian states
$nigerian_states = [
    'Abia', 'Adamawa', 'Akwa Ibom', 'Anambra', 'Bauchi', 'Bayelsa', 'Benue', 'Borno', 
    'Cross River', 'Delta', 'Ebonyi', 'Edo', 'Ekiti', 'Enugu', 'Gombe', 'Imo', 'Jigawa', 
    'Kaduna', 'Kano', 'Katsina', 'Kebbi', 'Kogi', 'Kwara', 'Lagos', 'Nasarawa', 'Niger', 
    'Ogun', 'Ondo', 'Osun', 'Oyo', 'Plateau', 'Rivers', 'Sokoto', 'Taraba', 'Yobe', 'Zamfara', 'FCT'
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?> - RoVo Nigeria</title>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@700&family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
    
    <style>
        :root {
            --primary: #D4A017;
            --secondary: #B8974A;
        }
        
        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 40px 0;
        }
        
        .wizard-container {
            max-width: 900px;
            margin: 0 auto;
        }
        
        .wizard-card {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            overflow: hidden;
        }
        
        .wizard-header {
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .wizard-header h2 {
            margin: 0;
            font-family: 'Playfair Display', serif;
        }
        
        .progress-steps {
            display: flex;
            justify-content: space-between;
            margin: 30px 0;
            padding: 0 30px;
        }
        
        .progress-step {
            flex: 1;
            text-align: center;
            position: relative;
        }
        
        .progress-step:not(:last-child)::after {
            content: '';
            position: absolute;
            top: 20px;
            left: 50%;
            right: -50%;
            height: 2px;
            background: #ddd;
            z-index: -1;
        }
        
        .progress-step.active:not(:last-child)::after {
            background: var(--primary);
        }
        
        .step-number {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #ddd;
            color: #666;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            margin-bottom: 10px;
        }
        
        .progress-step.active .step-number,
        .progress-step.completed .step-number {
            background: var(--primary);
            color: white;
        }
        
        .step-label {
            font-size: 0.85rem;
            color: #666;
        }
        
        .progress-step.active .step-label {
            color: var(--primary);
            font-weight: 600;
        }
        
        .wizard-body {
            padding: 40px;
        }
        
        .form-section {
            margin-bottom: 30px;
        }
        
        .form-section h5 {
            color: var(--primary);
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid var(--primary);
        }
        
        .btn-primary {
            background: var(--primary);
            border-color: var(--primary);
        }
        
        .btn-primary:hover {
            background: var(--secondary);
            border-color: var(--secondary);
        }
    </style>
</head>
<body>
    <div class="wizard-container">
        <div class="wizard-card">
            <div class="wizard-header">
                <h2>Complete Your Profile</h2>
                <p class="mb-0">Fill in your details to start applying for properties</p>
            </div>
            
            <!-- Progress Steps -->
            <div class="progress-steps">
                <div class="progress-step <?php echo $step >= 1 ? 'active' : ''; ?> <?php echo $step > 1 ? 'completed' : ''; ?>">
                    <div class="step-number">1</div>
                    <div class="step-label">Personal Info</div>
                </div>
                <div class="progress-step <?php echo $step >= 2 ? 'active' : ''; ?> <?php echo $step > 2 ? 'completed' : ''; ?>">
                    <div class="step-number">2</div>
                    <div class="step-label">Identity</div>
                </div>
                <div class="progress-step <?php echo $step >= 3 ? 'active' : ''; ?> <?php echo $step > 3 ? 'completed' : ''; ?>">
                    <div class="step-number">3</div>
                    <div class="step-label">Employment</div>
                </div>
                <div class="progress-step <?php echo $step >= 4 ? 'active' : ''; ?> <?php echo $step > 4 ? 'completed' : ''; ?>">
                    <div class="step-number">4</div>
                    <div class="step-label">Guarantors</div>
                </div>
                <div class="progress-step <?php echo $step >= 5 ? 'active' : ''; ?>">
                    <div class="step-number">5</div>
                    <div class="step-label">Review</div>
                </div>
            </div>
            
            <!-- Form Body -->
            <div class="wizard-body">
                <?php if (!empty($errors)): ?>
                <div class="alert alert-danger">
                    <ul class="mb-0">
                        <?php foreach ($errors as $error): ?>
                            <li><?php echo htmlspecialchars($error); ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                <?php endif; ?>
                
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="csrf_token" value="<?php echo Security::generateCSRFToken(); ?>">
                    <input type="hidden" name="step" value="<?php echo $step; ?>">
                    
                    <?php include "profile-steps/step-{$step}.php"; ?>
                    
                    <div class="d-flex justify-content-between mt-4">
                        <?php if ($step > 1): ?>
                        <a href="?step=<?php echo $step - 1; ?>" class="btn btn-outline-secondary">
                            <i class="fas fa-arrow-left"></i> Previous
                        </a>
                        <?php else: ?>
                        <div></div>
                        <?php endif; ?>
                        
                        <button type="submit" class="btn btn-primary">
                            <?php echo $step < $max_step ? 'Next Step' : 'Submit Profile'; ?>
                            <i class="fas fa-arrow-right"></i>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>