<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/middleware.php';

// Ensure user is a customer
require_customer();

// Initialize $pdo if not already set
if (!isset($pdo)) {
    $pdo = require_once __DIR__ . '/../config/database.php';
}
// Table creation handled by database.php

// Get current step from URL
$currentStep = $_GET['step'] ?? 1;
// Get service type from URL or fall back to session
$serviceType = $_GET['service'] ?? ($_SESSION['master_service_form']['service_type'] ?? '');
$currentStep = (int)$currentStep;

// Validate step range
if ($currentStep < 1 || $currentStep > 8) {
    $currentStep = 1;
}

// Initialize form data in session
if (!isset($_SESSION['master_service_form'])) {
    $_SESSION['master_service_form'] = [
        'step' => 1,
        'service_type' => $serviceType, // Use detected service type
        'universal_info' => [],
        'service_specific' => [],
        'files' => []
    ];
}

// Sync service type to session if provided in URL and different
if (!empty($_GET['service']) && $_SESSION['master_service_form']['service_type'] !== $_GET['service']) {
    $_SESSION['master_service_form']['service_type'] = $_GET['service'];
}

// Load user's reusable profile data if available
$userId = $_SESSION['user']['id'] ?? null;
$reusableProfile = [];
if ($userId) {
    $stmt = $pdo->prepare("SELECT * FROM user_profiles WHERE user_id = ?");
    $stmt->execute([$userId]);
    $reusableProfile = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
}

// Merge reusable profile into universal info on first load
if ($currentStep === 2 && empty($_SESSION['master_service_form']['universal_info']) && !empty($reusableProfile)) {
    $_SESSION['master_service_form']['universal_info'] = [
        'full_name' => $reusableProfile['full_name'] ?? $_SESSION['user']['full_name'] ?? '',
        'email' => $reusableProfile['email'] ?? $_SESSION['user']['email'] ?? '',
        'phone' => $reusableProfile['phone'] ?? '',
        'date_of_birth' => $reusableProfile['date_of_birth'] ?? '',
        'nationality' => $reusableProfile['nationality'] ?? 'Nigerian',
        'gender' => $reusableProfile['gender'] ?? '',
        'business_name' => $reusableProfile['business_name'] ?? '',
        'business_address' => $reusableProfile['business_address'] ?? '',
        'nature_of_business' => $reusableProfile['nature_of_business'] ?? '',
        'id_type' => $reusableProfile['id_type'] ?? '',
        'id_number' => $reusableProfile['id_number'] ?? '',
        'id_document_path' => $reusableProfile['id_document_path'] ?? '',
        'passport_path' => $reusableProfile['passport_path'] ?? '',
        'signature_path' => $reusableProfile['signature_path'] ?? '',
        'residential_address' => $reusableProfile['residential_address'] ?? '',
        'city' => $reusableProfile['city'] ?? '',
        'state' => $reusableProfile['state'] ?? '',
        'country' => $reusableProfile['country'] ?? 'Nigeria',
        'next_of_kin_name' => $reusableProfile['next_of_kin_name'] ?? '',
        'next_of_kin_phone' => $reusableProfile['next_of_kin_phone'] ?? '',
        'next_of_kin_relationship' => $reusableProfile['next_of_kin_relationship'] ?? ''
    ];
}

// Handle form submission BEFORE including header (to avoid headers already sent error)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $_SESSION['debug_last_post'] = $_POST;
    handleFormSubmission($currentStep, $serviceType, $pdo);
}

// NOW include header (after all potential header() redirects)
require_once __DIR__ . '/../includes/header.php';

function handleFormSubmission(int $step, string $serviceType, PDO $pdo): void {
    $data = $_POST;
    $files = $_FILES;
    
    $_SESSION['debug_info'] = "Step $step submitted, data keys: " . implode(', ', array_keys($data));
    
    // Validate and sanitize input
    $validatedData = validateStepData($step, $serviceType, $data);
    
    // Save to session
    if ($step === 1) {
        $submittedServiceType = $data['service_type'] ?? $serviceType;
        $_SESSION['master_service_form']['service_type'] = $submittedServiceType;
        $serviceType = $submittedServiceType;
    } elseif ($step === 2) {
        $_SESSION['master_service_form']['universal_info'] = $validatedData;
        // Save to reusable profile with files
        saveUserProfile($pdo, $validatedData, $files);
    } else {
        $_SESSION['master_service_form']['service_specific'][$step] = $validatedData;
    }
    
    // Handle file uploads for steps that need them
    if (!empty($files) && $step !== 2) {
        $uploadedFiles = handleFileUploads($step, $serviceType, $files);
        $_SESSION['master_service_form']['files'] = array_merge($_SESSION['master_service_form']['files'] ?? [], $uploadedFiles);
    }
    
    $_SESSION['master_service_form']['step'] = $step;
    
    // Redirect or process payment
    if (isset($data['save_later'])) {
        header('Location: /customer/dashboard.php');
        exit;
    } elseif (isset($data['next_step'])) {
        $nextStep = $step + 1;
        // Jump from 3 to 7 since 4,5,6 are empty
        if ($step === 3) $nextStep = 7;
        
        if ($nextStep <= 7) {
            $redirectUrl = "/customer/master-service.php?step=$nextStep";
            if ($serviceType) {
                $redirectUrl .= "&service=$serviceType";
            }
            header("Location: $redirectUrl");
            exit;
        }
    } elseif (isset($data['proceed_to_payment'])) {
        processPayment();
    }
}


function saveUserProfile(PDO $pdo, array $data, array $files = []): void {
    $userId = $_SESSION['user']['id'] ?? null;
    if (!$userId) return;
    
    // Handle file uploads first
    $uploadDir = __DIR__ . '/../uploads/profile/' . $userId . '/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    
    $filePaths = [];
    
    // Handle ID Document upload
    if (!empty($files['id_document']['tmp_name']) && $files['id_document']['error'] === UPLOAD_ERR_OK) {
        $ext = pathinfo($files['id_document']['name'], PATHINFO_EXTENSION);
        $filename = 'id_document_' . time() . '.' . $ext;
        if (move_uploaded_file($files['id_document']['tmp_name'], $uploadDir . $filename)) {
            $filePaths['id_document_path'] = '/uploads/profile/' . $userId . '/' . $filename;
        }
    }
    
    // Handle Passport Photo upload
    if (!empty($files['passport_photo']['tmp_name']) && $files['passport_photo']['error'] === UPLOAD_ERR_OK) {
        $ext = pathinfo($files['passport_photo']['name'], PATHINFO_EXTENSION);
        $filename = 'passport_' . time() . '.' . $ext;
        if (move_uploaded_file($files['passport_photo']['tmp_name'], $uploadDir . $filename)) {
            $filePaths['passport_path'] = '/uploads/profile/' . $userId . '/' . $filename;
        }
    }
    
    // Handle Signature upload
    if (!empty($files['signature']['tmp_name']) && $files['signature']['error'] === UPLOAD_ERR_OK) {
        $ext = pathinfo($files['signature']['name'], PATHINFO_EXTENSION);
        $filename = 'signature_' . time() . '.' . $ext;
        if (move_uploaded_file($files['signature']['tmp_name'], $uploadDir . $filename)) {
            $filePaths['signature_path'] = '/uploads/profile/' . $userId . '/' . $filename;
        }
    }
    
    // Build the SQL query dynamically
    $fields = [
        'full_name', 'email', 'phone', 'date_of_birth', 'nationality', 'gender',
        'business_name', 'business_address', 'nature_of_business',
        'id_type', 'id_number',
        'residential_address', 'city', 'state', 'country',
        'next_of_kin_name', 'next_of_kin_phone', 'next_of_kin_relationship'
    ];
    
    $insertFields = ['user_id'];
    $insertValues = [$userId];
    $updateSets = [];
    
    foreach ($fields as $field) {
        $insertFields[] = $field;
        $insertValues[] = $data[$field] ?? '';
        $updateSets[] = "$field = excluded.$field";
    }
    
    // Add file paths if any
    foreach ($filePaths as $field => $path) {
        $insertFields[] = $field;
        $insertValues[] = $path;
        $updateSets[] = "$field = excluded.$field";
    }
    
    $insertFields[] = 'updated_at';
    $insertValues[] = date('Y-m-d H:i:s');
    $updateSets[] = "updated_at = datetime('now')";
    
    $sql = "INSERT INTO user_profiles (" . implode(', ', $insertFields) . ") VALUES (" . 
           implode(', ', array_fill(0, count($insertValues), '?')) . ") 
           ON CONFLICT(user_id) DO UPDATE SET " . implode(', ', $updateSets);
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($insertValues);
}

function validateStepData(int $step, string $serviceType, array $data): array {
    $validated = [];
    
    switch ($step) {
        case 2:
            $validated = [
                'full_name' => sanitizeInput($data['full_name'] ?? ''),
                'email' => filter_var($data['email'] ?? '', FILTER_VALIDATE_EMAIL) ? $data['email'] : '',
                'phone' => sanitizeInput($data['phone'] ?? ''),
                'date_of_birth' => sanitizeInput($data['date_of_birth'] ?? ''),
                'nationality' => sanitizeInput($data['nationality'] ?? 'Nigerian'),
                'gender' => sanitizeInput($data['gender'] ?? ''),
                'business_name' => sanitizeInput($data['business_name'] ?? ''),
                'business_address' => sanitizeInput($data['business_address'] ?? ''),
                'nature_of_business' => sanitizeInput($data['nature_of_business'] ?? ''),
                'id_type' => sanitizeInput($data['id_type'] ?? ''),
                'id_number' => sanitizeInput($data['id_number'] ?? ''),
                'residential_address' => sanitizeInput($data['residential_address'] ?? ''),
                'city' => sanitizeInput($data['city'] ?? ''),
                'state' => sanitizeInput($data['state'] ?? ''),
                'country' => sanitizeInput($data['country'] ?? 'Nigeria'),
                'next_of_kin_name' => sanitizeInput($data['next_of_kin_name'] ?? ''),
                'next_of_kin_phone' => sanitizeInput($data['next_of_kin_phone'] ?? ''),
                'next_of_kin_relationship' => sanitizeInput($data['next_of_kin_relationship'] ?? ''),
            ];
            break;
            
        case 3:
            $validated = [
                'proposed_name_1' => sanitizeInput($data['proposed_name_1'] ?? ''),
                'proposed_name_2' => sanitizeInput($data['proposed_name_2'] ?? ''),
                'details' => sanitizeInput($data['details'] ?? '')
            ];
            break;

            
        case 7:
            $validated = ['confirmations' => $data['confirmations'] ?? []];
            break;
    }
    
    return $validated;
}

function sanitizeInput(string $input): string {
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}

function processPayment(): void {
    $pdo = require __DIR__ . '/../config/database.php';
    $formData = $_SESSION['master_service_form'];
    $userId = $_SESSION['user']['id'];
    $serviceSlug = $formData['service_type'];

    try {
        $pdo->beginTransaction();

        // Map service slug to ID and get fees
        $svcStmt = $pdo->prepare("SELECT id, base_price FROM services WHERE slug = ?");
        $svcStmt->execute([$serviceSlug]);
        $service = $svcStmt->fetch();

        if (!$service) {
            throw new Exception("Invalid service selected.");
        }

        $serviceId = (int)$service['id'];
        $basePrice = (float)$service['base_price'];
        
        // Split price (for simulation: 30% CAC fee, 70% Service fee)
        $cacFee = round($basePrice * 0.3, 2);
        $serviceFee = $basePrice - $cacFee;

        // Insert into applications table (Unified Schema)
        $appStmt = $pdo->prepare("
            INSERT INTO applications (user_id, service_id, status, cac_fee, service_fee, total_price, created_at, updated_at)
            VALUES (?, ?, 'draft', ?, ?, ?, datetime('now'), datetime('now'))
        ");
        $appStmt->execute([$userId, $serviceId, $cacFee, $serviceFee, $basePrice]);
        $appId = (int)$pdo->lastInsertId();

        // Insert into application_details (Unified Schema)
        $universal = $formData['universal_info'] ?? [];
        $specific = $formData['service_specific'][3] ?? []; // Step 3 usually has names/details

        $detStmt = $pdo->prepare("
            INSERT INTO application_details (
                application_id, full_name, email, phone, 
                proposed_name_1, proposed_name_2, nature_of_business, business_address,
                id_document_path, passport_path
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        
        $detStmt->execute([
            $appId,
            $universal['full_name'] ?? $_SESSION['user']['full_name'],
            $universal['email'] ?? $_SESSION['user']['email'],
            $universal['phone'] ?? '',
            $specific['proposed_name_1'] ?? $specific['alternative_names'] ?? '',
            $specific['proposed_name_2'] ?? '',
            $universal['nature_of_business'] ?? $specific['business_nature'] ?? '',
            $universal['business_address'] ?? $specific['principal_address'] ?? '',
            $universal['id_document_path'] ?? null,
            $universal['passport_path'] ?? null
        ]);

        $pdo->commit();
        unset($_SESSION['master_service_form']);
        
        header("Location: /customer/view_application.php?id=$appId");
        exit;

    } catch (Exception $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        $_SESSION['error'] = "Error: " . $e->getMessage();
        header("Location: /customer/master-service.php?step=7");
        exit;
    }
}


$stepData = $_SESSION['master_service_form']['service_specific'][$currentStep] ?? [];
$universalData = $_SESSION['master_service_form']['universal_info'] ?? [];
$selectedService = $_SESSION['master_service_form']['service_type'] ?? '';

$pageTitle = 'Service Application - Step ' . $currentStep;
?>

<style>
.master-service-container { max-width: 900px; margin: 40px auto; padding: 0 20px; }
.step-progress { display: flex; justify-content: space-between; margin-bottom: 40px; position: relative; }
.step-progress::before { content: ''; position: absolute; top: 20px; left: 0; right: 0; height: 4px; background: #e5e7eb; z-index: 0; }
.step-item { position: relative; z-index: 1; text-align: center; flex: 1; }
.step-number { width: 44px; height: 44px; border-radius: 50%; background: white; border: 3px solid #e5e7eb; display: flex; align-items: center; justify-content: center; font-weight: 700; margin: 0 auto 8px; transition: all 0.3s ease; }
.step-item.active .step-number { border-color: #10b981; background: #10b981; color: white; }
.step-item.completed .step-number { border-color: #10b981; background: #10b981; color: white; }
.step-item.active .step-label { color: #10b981; font-weight: 700; }
.step-label { display: block; font-size: 11px; margin-top: 4px; color: #9ca3af; font-weight: 600; text-transform: uppercase; }
.step-title { font-size: 28px; font-weight: 700; color: #1f2937; margin-bottom: 8px; }
.step-subtitle { color: #6b7280; margin-bottom: 32px; font-size: 16px; }
.form-group { margin-bottom: 24px; }
.form-group label { display: block; font-weight: 600; color: #374151; margin-bottom: 8px; }
.form-group input, .form-group select, .form-group textarea { width: 100%; padding: 12px 16px; border: 2px solid #e5e7eb; border-radius: 10px; font-size: 15px; transition: border-color 0.2s; }
.form-group input:focus, .form-group select:focus, .form-group textarea:focus { outline: none; border-color: #10b981; }
.checkbox-group { display: grid; gap: 12px; }
.checkbox-option { display: flex; align-items: flex-start; gap: 12px; padding: 16px; border: 2px solid #e5e7eb; border-radius: 10px; cursor: pointer; transition: all 0.2s ease; }
.checkbox-option:hover { border-color: #10b981; }
.checkbox-option input[type="checkbox"] { width: 20px; height: 20px; margin-top: 2px; accent-color: #10b981; }
.button-group { display: flex; gap: 16px; margin-top: 32px; }
.btn { padding: 14px 28px; border-radius: 10px; font-weight: 600; font-size: 15px; cursor: pointer; transition: all 0.2s; text-decoration: none; display: inline-flex; align-items: center; gap: 8px; border: none; }
.btn-primary { background: #10b981; color: white; }
.btn-primary:hover { background: #059669; }
.btn-secondary { background: #f3f4f6; color: #374151; }
.btn-secondary:hover { background: #e5e7eb; }
@media (max-width: 640px) { .step-label { display: none; } .button-group { flex-direction: column; } }
</style>

<div class="master-service-container">
    <div class="step-progress">
        <?php 
        $steps = [
            1 => 'Service',
            2 => 'Client',
            3 => 'Details',
            7 => 'Confirm'
        ];
        foreach ($steps as $i => $label): ?>
            <div class="step-item <?= $i === $currentStep ? 'active' : ($i < $currentStep ? 'completed' : '') ?>">
                <div class="step-number"><?= ($i < $currentStep && $currentStep != 7) || ($currentStep == 7 && $i < 7) ? '✓' : ($i == 7 ? 4 : $i) ?></div>
                <div class="step-label"><?= $label ?></div>
            </div>
        <?php endforeach; ?>
    </div>


    <?php renderStepContent($currentStep, $serviceType, $stepData, $universalData); ?>
</div>

<?php
function renderStepContent(int $step, string $serviceType, array $stepData, array $universalData): void {
    switch ($step) {
        case 1: renderStep1($serviceType, $step); break;
        case 2: renderStep2($universalData, $step, $serviceType); break;
        case 3: renderStep3($serviceType, $stepData, $step); break;
        case 7: renderStep7($stepData, $step, $serviceType); break;
    }
}

function renderStep1(string $serviceType, int $currentStep): void {
    $services = [
        ['id' => 'business_name', 'name' => 'Business Name Registration', 'desc' => 'Register a business name with CAC', 'icon' => '🏢'],
        ['id' => 'limited_company', 'name' => 'Limited Company Registration', 'desc' => 'Incorporate a private limited company', 'icon' => '🏛️'],
        ['id' => 'ngo', 'name' => 'NGO/Incorporated Trustee', 'desc' => 'Register a non-profit organization', 'icon' => '🤝'],
        ['id' => 'trademark', 'name' => 'Trademark Registration', 'desc' => 'Protect your brand and intellectual property', 'icon' => '™️'],
        ['id' => 'scuml', 'name' => 'SCUML Registration', 'desc' => 'Special Control Unit Against Money Laundering', 'icon' => '🛡️'],
        ['id' => 'tin', 'name' => 'TIN Registration', 'desc' => 'Tax Identification Number for individuals', 'icon' => '📋'],
        ['id' => 'post_incorporation', 'name' => 'Post Incorporation Services', 'desc' => 'Changes, updates, and compliance services', 'icon' => '📝'],
    ];
    ?>
    <h1 class="step-title">Step 1 — Service Selection</h1>
    <p class="step-subtitle">Select the service you want to register for</p>
    <form method="POST">
        <div class="form-group">
            <div class="checkbox-group">
                <?php foreach ($services as $svc): ?>
                <label class="checkbox-option">
                    <input type="radio" name="service_type" value="<?= $svc['id'] ?>" <?= $serviceType === $svc['id'] ? 'checked' : '' ?> required>
                    <div>
                        <strong><?= $svc['icon'] ?> <?= $svc['name'] ?></strong>
                        <div style="font-size: 13px; color: #6b7280; margin-top: 4px;"><?= $svc['desc'] ?></div>
                    </div>
                </label>
                <?php endforeach; ?>
            </div>
        </div>
        <div class="button-group">
            <button type="submit" name="next_step" class="btn btn-primary">Proceed →</button>
        </div>
    </form>
    <?php
}

function renderStep2(array $data, int $currentStep, string $serviceType): void {
    $hasProfileData = !empty($data['phone']) || !empty($data['date_of_birth']);
    ?>
    <h1 class="step-title">Step 2 — Client Information</h1>
    <p class="step-subtitle"><?= $hasProfileData ? 'Review your saved information (editable for this application)' : 'Provide your personal details. This information will be saved for future applications.' ?></p>
    
    <?php if ($hasProfileData): ?>
    <div style="background: #f0fdf4; border: 1px solid #86efac; border-radius: 10px; padding: 16px; margin-bottom: 24px;">
        <div style="display: flex; align-items: center; gap: 12px;">
            <div style="font-size: 24px;">✓</div>
            <div>
                <div style="font-weight: 600; color: #166534;">Profile Data Loaded</div>
                <div style="font-size: 14px; color: #15803d;">Your saved information has been pre-filled. You can update any field.</div>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <form method="POST" enctype="multipart/form-data">
        <!-- Personal Information Section -->
        <div class="form-section" style="margin-bottom: 32px;">
            <h3 style="font-size: 16px; font-weight: 600; color: #374151; margin-bottom: 16px; padding-bottom: 8px; border-bottom: 2px solid #e5e7eb;">Personal Information</h3>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 16px;">
                <div class="form-group">
                    <label>Full Name *</label>
                    <input type="text" name="full_name" value="<?= htmlspecialchars($data['full_name'] ?? '') ?>" required>
                </div>
                <div class="form-group">
                    <label>Email Address *</label>
                    <input type="email" name="email" value="<?= htmlspecialchars($data['email'] ?? '') ?>" required>
                </div>
                <div class="form-group">
                    <label>Phone Number *</label>
                    <input type="tel" name="phone" value="<?= htmlspecialchars($data['phone'] ?? '') ?>" required placeholder="e.g., +234 801 234 5678">
                </div>
                <div class="form-group">
                    <label>Date of Birth</label>
                    <input type="date" name="date_of_birth" value="<?= htmlspecialchars($data['date_of_birth'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label>Nationality</label>
                    <input type="text" name="nationality" value="<?= htmlspecialchars($data['nationality'] ?? 'Nigerian') ?>">
                </div>
                <div class="form-group">
                    <label>Gender</label>
                    <select name="gender">
                        <option value="">Select...</option>
                        <option value="Male" <?= ($data['gender'] ?? '') === 'Male' ? 'selected' : '' ?>>Male</option>
                        <option value="Female" <?= ($data['gender'] ?? '') === 'Female' ? 'selected' : '' ?>>Female</option>
                        <option value="Other" <?= ($data['gender'] ?? '') === 'Other' ? 'selected' : '' ?>>Other</option>
                    </select>
                </div>
            </div>
        </div>

        <!-- Address Information Section -->
        <div class="form-section" style="margin-bottom: 32px;">
            <h3 style="font-size: 16px; font-weight: 600; color: #374151; margin-bottom: 16px; padding-bottom: 8px; border-bottom: 2px solid #e5e7eb;">Address Information</h3>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 16px;">
                <div class="form-group" style="grid-column: 1 / -1;">
                    <label>Residential Address</label>
                    <textarea name="residential_address" rows="2" placeholder="Full residential address"><?= htmlspecialchars($data['residential_address'] ?? '') ?></textarea>
                </div>
                <div class="form-group">
                    <label>City</label>
                    <input type="text" name="city" value="<?= htmlspecialchars($data['city'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label>State</label>
                    <input type="text" name="state" value="<?= htmlspecialchars($data['state'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label>Country</label>
                    <input type="text" name="country" value="<?= htmlspecialchars($data['country'] ?? 'Nigeria') ?>">
                </div>
            </div>
        </div>

        <!-- Business Information Section -->
        <div class="form-section" style="margin-bottom: 32px;">
            <h3 style="font-size: 16px; font-weight: 600; color: #374151; margin-bottom: 16px; padding-bottom: 8px; border-bottom: 2px solid #e5e7eb;">Business Information</h3>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 16px;">
                <div class="form-group">
                    <label>Business Name (if applicable)</label>
                    <input type="text" name="business_name" value="<?= htmlspecialchars($data['business_name'] ?? '') ?>" placeholder="Existing business name">
                </div>
                <div class="form-group" style="grid-column: 1 / -1;">
                    <label>Business Address</label>
                    <textarea name="business_address" rows="2" placeholder="Business/office address"><?= htmlspecialchars($data['business_address'] ?? '') ?></textarea>
                </div>
                <div class="form-group" style="grid-column: 1 / -1;">
                    <label>Nature of Business</label>
                    <textarea name="nature_of_business" rows="2" placeholder="Describe what your business does"><?= htmlspecialchars($data['nature_of_business'] ?? '') ?></textarea>
                </div>
            </div>
        </div>

        <!-- Identity Documents Section -->
        <div class="form-section" style="margin-bottom: 32px;">
            <h3 style="font-size: 16px; font-weight: 600; color: #374151; margin-bottom: 16px; padding-bottom: 8px; border-bottom: 2px solid #e5e7eb;">Identity Documents</h3>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 16px;">
                <div class="form-group">
                    <label>ID Type</label>
                    <select name="id_type">
                        <option value="">Select ID Type...</option>
                        <option value="NIN" <?= ($data['id_type'] ?? '') === 'NIN' ? 'selected' : '' ?>>National ID (NIN)</option>
                        <option value="Passport" <?= ($data['id_type'] ?? '') === 'Passport' ? 'selected' : '' ?>>International Passport</option>
                        <option value="Voters Card" <?= ($data['id_type'] ?? '') === 'Voters Card' ? 'selected' : '' ?>>Voter's Card</option>
                        <option value="Drivers License" <?= ($data['id_type'] ?? '') === 'Drivers License' ? 'selected' : '' ?>>Driver's License</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>ID Number</label>
                    <input type="text" name="id_number" value="<?= htmlspecialchars($data['id_number'] ?? '') ?>" placeholder="Enter ID number">
                </div>
            </div>
            
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-top: 16px;">
                <div class="form-group">
                    <label>ID Document (PDF, JPG, PNG - Max 5MB)</label>
                    <?php if (!empty($data['id_document_path'])): ?>
                    <div style="background: #f3f4f6; padding: 8px 12px; border-radius: 6px; margin-bottom: 8px; font-size: 13px;">
                        ✓ <a href="<?= htmlspecialchars($data['id_document_path']) ?>" target="_blank" style="color: #10b981;">View saved document</a>
                    </div>
                    <?php endif; ?>
                    <input type="file" name="id_document" accept=".pdf,.jpg,.jpeg,.png" style="padding: 8px; border: 2px dashed #e5e7eb; border-radius: 8px; width: 100%;">
                    <small style="color: #6b7280; font-size: 12px;">Upload new to replace existing</small>
                </div>
                <div class="form-group">
                    <label>Passport Photo (JPG, PNG - Max 2MB)</label>
                    <?php if (!empty($data['passport_path'])): ?>
                    <div style="background: #f3f4f6; padding: 8px 12px; border-radius: 6px; margin-bottom: 8px; font-size: 13px;">
                        ✓ <a href="<?= htmlspecialchars($data['passport_path']) ?>" target="_blank" style="color: #10b981;">View saved photo</a>
                    </div>
                    <?php endif; ?>
                    <input type="file" name="passport_photo" accept=".jpg,.jpeg,.png" style="padding: 8px; border: 2px dashed #e5e7eb; border-radius: 8px; width: 100%;">
                    <small style="color: #6b7280; font-size: 12px;">Upload new to replace existing</small>
                </div>
                <div class="form-group">
                    <label>Signature (JPG, PNG - Max 2MB)</label>
                    <?php if (!empty($data['signature_path'])): ?>
                    <div style="background: #f3f4f6; padding: 8px 12px; border-radius: 6px; margin-bottom: 8px; font-size: 13px;">
                        ✓ <a href="<?= htmlspecialchars($data['signature_path']) ?>" target="_blank" style="color: #10b981;">View saved signature</a>
                    </div>
                    <?php endif; ?>
                    <input type="file" name="signature" accept=".jpg,.jpeg,.png" style="padding: 8px; border: 2px dashed #e5e7eb; border-radius: 8px; width: 100%;">
                    <small style="color: #6b7280; font-size: 12px;">Upload new to replace existing</small>
                </div>
            </div>
        </div>

        <!-- Next of Kin Section -->
        <div class="form-section" style="margin-bottom: 32px;">
            <h3 style="font-size: 16px; font-weight: 600; color: #374151; margin-bottom: 16px; padding-bottom: 8px; border-bottom: 2px solid #e5e7eb;">Next of Kin</h3>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 16px;">
                <div class="form-group">
                    <label>Full Name</label>
                    <input type="text" name="next_of_kin_name" value="<?= htmlspecialchars($data['next_of_kin_name'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label>Phone Number</label>
                    <input type="tel" name="next_of_kin_phone" value="<?= htmlspecialchars($data['next_of_kin_phone'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label>Relationship</label>
                    <input type="text" name="next_of_kin_relationship" value="<?= htmlspecialchars($data['next_of_kin_relationship'] ?? '') ?>" placeholder="e.g., Spouse, Parent, Sibling">
                </div>
            </div>
        </div>

        <div class="button-group">
            <a href="/customer/master-service.php?step=1" class="btn btn-secondary">← Back</a>
            <button type="submit" name="save_later" class="btn btn-secondary">Save & Continue Later</button>
            <button type="submit" name="next_step" class="btn btn-primary">Proceed →</button>
        </div>
    </form>
    <?php
}

function renderStep3(string $serviceType, array $data, int $currentStep): void {
    ?>
    <h1 class="step-title">Step 3 — Registration Details</h1>
    <p class="step-subtitle">Please provide the details for your registration</p>
    <form method="POST">
        <div class="form-group">
            <label>Proposed Name 1 *</label>
            <input type="text" name="proposed_name_1" value="<?= htmlspecialchars($data['proposed_name_1'] ?? '') ?>" required placeholder="Your first choice for business name">
        </div>
        <div class="form-group">
            <label>Proposed Name 2 (Alternative) *</label>
            <input type="text" name="proposed_name_2" value="<?= htmlspecialchars($data['proposed_name_2'] ?? '') ?>" required placeholder="Alternative if first name is rejected">
        </div>
        <div class="form-group">
            <label>Additional Information</label>
            <textarea name="details" placeholder="Any other specific instructions..." rows="3"><?= htmlspecialchars($data['details'] ?? '') ?></textarea>
        </div>
        <div class="button-group">
            <a href="/customer/master-service.php?step=2&service=<?= htmlspecialchars($serviceType) ?>" class="btn btn-secondary">← Back</a>
            <button type="submit" name="next_step" class="btn btn-primary">Proceed →</button>
        </div>
    </form>
    <?php
}


function renderStep7(array $data, int $currentStep, string $serviceType): void {
    ?>
    <h1 class="step-title">Step 7 — Confirmation & Authorization</h1>
    <p class="step-subtitle">Please review and confirm the following statements:</p>
    
    <?php if (isset($_SESSION['error'])): ?>
    <div style="background: #fef2f2; border: 1px solid #fecaca; border-radius: 8px; padding: 16px; margin-bottom: 24px; color: #991b1b;">
        <strong>Error:</strong> <?= htmlspecialchars($_SESSION['error']) ?>
        <?php unset($_SESSION['error']); ?>
    </div>
    <?php endif; ?>
    
    <form method="POST">
        <div class="form-group">
            <div class="checkbox-group">
                <div class="checkbox-option">
                    <input type="checkbox" name="confirmations[]" value="information_accuracy" required>
                    <div><strong>I confirm that all information provided is accurate</strong></div>
                </div>
                <div class="checkbox-option">
                    <input type="checkbox" name="confirmations[]" value="authorization" required>
                    <div><strong>I authorize Go Legal to process this application</strong></div>
                </div>
                <div class="checkbox-option">
                    <input type="checkbox" name="confirmations[]" value="terms" required>
                    <div><strong>I agree to the terms and conditions</strong></div>
                </div>
            </div>
        </div>
        <div class="button-group">
            <a href="/customer/master-service.php?step=6&service=<?= htmlspecialchars($serviceType) ?>" class="btn btn-secondary">← Back</a>
            <button type="submit" name="proceed_to_payment" value="1" class="btn btn-primary">Proceed to Payment →</button>
        </div>
    </form>
    <?php
}

function handleFileUploads(int $step, string $serviceType, array $files): array {
    return [];
}

require_once __DIR__ . '/../includes/footer.php';
?>
