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

$uid = $_SESSION['user']['id'];
$step = (int)($_GET['step'] ?? 1);
$serviceType = $_GET['type'] ?? 'business_name';

// Professional intake validation
function validateIntakeData($data) {
    $errors = [];
    
    // Basic validation
    if (empty($data['full_name'])) $errors[] = 'Full legal name is required';
    if (empty($data['email'])) $errors[] = 'Email is required';
    if (empty($data['phone'])) $errors[] = 'Phone number is required';
    if (empty($data['address'])) $errors[] = 'Address is required';
    
    // Email validation
    if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Invalid email address';
    }
    
    // Phone validation (Nigerian format)
    if (!preg_match('/^(\+234|0)?[789][01]\d{8}$/', $data['phone'])) {
        $errors[] = 'Invalid Nigerian phone number format';
    }
    
    return $errors;
}

function createVerificationCheckpoints($applicationId, $serviceType) {
    global $pdo;
    $checkpoints = [];
    
    switch ($serviceType) {
        case 'business_name':
            $checkpoints = ['name_screening', 'document_verification', 'compliance_check'];
            break;
        case 'company':
            $checkpoints = ['name_screening', 'document_verification', 'share_structure', 'compliance_check', 'risk_assessment'];
            break;
        case 'ngo':
            $checkpoints = ['name_screening', 'document_verification', 'compliance_check', 'risk_assessment'];
            break;
    }
    
    foreach ($checkpoints as $checkpoint) {
        $stmt = $pdo->prepare("INSERT INTO verification_checkpoints (application_id, checkpoint_type, status, created_at, updated_at) VALUES (?, ?, 'pending', ?, ?)");
        $stmt->execute([$applicationId, $checkpoint, date('c'), date('c')]);
    }
}

// Step 1: Service Selection & Initial Screening
if ($step === 1) {
    if (is_post()) {
        ensure_csrf();
        $serviceId = (int)($_POST['service_id'] ?? 0);
        $svc = $pdo->prepare("SELECT * FROM services WHERE id=? AND status='active'"); 
        $svc->execute([$serviceId]); 
        $service = $svc->fetch();
        
        if ($service) {
            // Create application with enhanced tracking
            $now = date('c');
            $stmt = $pdo->prepare('INSERT INTO applications (user_id, service_id, status, total_price, cac_fee, service_fee, service_category, priority_level, risk_score, internal_status, created_at, updated_at) VALUES (?,?,"draft",0,0,0,?,"normal",0,"new",?,?)');
            $stmt->execute([$uid, $serviceId, $service['service_type'], $now, $now]);
            $aid = (int)$pdo->lastInsertId();
            
            // Create verification checkpoints based on service type
            createVerificationCheckpoints($aid, $service['service_type']);
            
            redirect('/customer/professional_intake.php?step=2&id=' . $aid . '&type=' . $service['service_type']);
        }
    }
    
    // Get services by category
    $services = $pdo->query("SELECT * FROM services WHERE status='active' ORDER BY service_type, service_name")->fetchAll();
    $businessServices = array_filter($services, fn($s) => $s['service_type'] === 'business_name');
    $companyServices = array_filter($services, fn($s) => $s['service_type'] === 'company');
    $ngoServices = array_filter($services, fn($s) => $s['service_type'] === 'ngo');
    
    include __DIR__ . '/../includes/header.php';
    ?>
    <style>
    .service-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-bottom: 32px; }
    .service-card { background: #fff; border: 1px solid var(--border); border-radius: 16px; padding: 24px; cursor: pointer; transition: all 0.3s; }
    .service-card:hover { transform: translateY(-4px); box-shadow: 0 12px 20px -5px rgba(0,0,0,0.1); border-color: var(--primary); }
    .service-title { font-size: 18px; font-weight: 700; color: var(--text); margin-bottom: 8px; }
    .service-price { font-size: 24px; font-weight: 800; color: var(--primary); margin-bottom: 8px; }
    .service-description { font-size: 14px; color: var(--muted); line-height: 1.6; }
    .service-features { margin-top: 16px; }
    .feature { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; font-size: 13px; }
    .feature-icon { color: #10b981; }
    </style>
    
    <div class="admin-header">
        <h1 class="dashboard-title">Professional Service Selection</h1>
        <p class="dashboard-subtitle">Choose your business registration service with enhanced verification and compliance tracking</p>
    </div>
    
    <form method="post">
        <?=csrf_field()?>
        
        <h2 style="margin: 32px 0 16px; color: var(--text);">📋 Business Name Registration</h2>
        <div class="service-grid">
            <?php foreach ($businessServices as $service): ?>
                <div class="service-card" onclick="selectService(<?=$service['id']?>)">
                    <h3 class="service-title"><?=e($service['service_name'])?></h3>
                    <div class="service-price">₦<?=number_format($service['cac_fee'] + $service['service_fee'])?></div>
                    <div class="service-description"><?=e($service['description'] ?? 'Fast and reliable business name registration with CAC')?></div>
                    <div class="service-features">
                        <div class="feature"><span class="feature-icon">✓</span> Name reservation</div>
                        <div class="feature"><span class="feature-icon">✓</span> CAC registration</div>
                        <div class="feature"><span class="feature-icon">✓</span> Certificate</div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        
        <h2 style="margin: 32px 0 16px; color: var(--text);">🏢 Company Registration</h2>
        <div class="service-grid">
            <?php foreach ($companyServices as $service): ?>
                <div class="service-card" onclick="selectService(<?=$service['id']?>)">
                    <h3 class="service-title"><?=e($service['service_name'])?></h3>
                    <div class="service-price">₦<?=number_format($service['cac_fee'] + $service['service_fee'])?></div>
                    <div class="service-description"><?=e($service['description'] ?? 'Complete company incorporation with MEMART and shareholder structure')?></div>
                    <div class="service-features">
                        <div class="feature"><span class="feature-icon">✓</span> Name reservation</div>
                        <div class="feature"><span class="feature-icon">✓</span> Company incorporation</div>
                        <div class="feature"><span class="feature-icon">✓</span> MEMART filing</div>
                        <div class="feature"><span class="feature-icon">✓</span> Shareholder certificates</div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        
        <h2 style="margin: 32px 0 16px; color: var(--text);">🏛️ NGO Registration</h2>
        <div class="service-grid">
            <?php foreach ($ngoServices as $service): ?>
                <div class="service-card" onclick="selectService(<?=$service['id']?>)">
                    <h3 class="service-title"><?=e($service['service_name'])?></h3>
                    <div class="service-price">₦<?=number_format($service['cac_fee'] + $service['service_fee'])?></div>
                    <div class="service-description"><?=e($service['description'] ?? 'NGO incorporation with trustee structure and compliance')?></div>
                    <div class="service-features">
                        <div class="feature"><span class="feature-icon">✓</span> Trustee setup</div>
                        <div class="feature"><span class="feature-icon">✓</span> Constitution filing</div>
                        <div class="feature"><span class="feature-icon">✓</span> CAC incorporation</div>
                        <div class="feature"><span class="feature-icon">✓</span> Compliance guide</div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </form>
    
    <script>
    function selectService(serviceId) {
        const form = document.querySelector('form');
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'service_id';
        input.value = serviceId;
        form.appendChild(input);
        form.submit();
    }
    </script>
    
    <?php
    include __DIR__ . '/../includes/footer.php';
    exit;
}

// Step 2: Enhanced Client Intake Form
if ($step === 2) {
    $aid = (int)($_GET['id'] ?? 0);
    $app = $pdo->prepare('SELECT * FROM applications WHERE id=? AND user_id=?'); 
    $app->execute([$aid, $uid]); 
    $application = $app->fetch();
    
    if (!$application || $application['status'] !== 'draft') {
        set_flash('error', 'Invalid application or already submitted');
        redirect('/customer/dashboard.php');
    }
    
    if (is_post()) {
        ensure_csrf();
        $data = $_POST;
        $errors = validateIntakeData($data);
        
        if (empty($errors)) {
            // Save to application_details
            $stmt = $pdo->prepare('INSERT OR REPLACE INTO application_details (application_id, proposed_name_1, proposed_name_2, nature_of_business, business_address, full_name, email, phone) VALUES (?,?,?,?,?,?,?,?)');
            $stmt->execute([
                $aid,
                $data['proposed_name_1'],
                $data['proposed_name_2'],
                $data['nature_of_business'],
                $data['business_address'],
                $data['full_name'],
                $data['email'],
                $data['phone']
            ]);
            
            // Update application status
            $pdo->prepare("UPDATE applications SET status='submitted', updated_at=? WHERE id=?")->execute([date('c'), $aid]);
            
            set_flash('success', 'Application submitted successfully! We will review and verify your information.');
            redirect('/customer/view_application.php?id=' . $aid);
        }
    }
    
    include __DIR__ . '/../includes/header.php';
    ?>
    <style>
    .intake-form { max-width: 800px; margin: 0 auto; }
    .form-section { background: #fff; border: 1px solid var(--border); border-radius: 16px; padding: 32px; margin-bottom: 24px; }
    .section-title { font-size: 20px; font-weight: 700; color: var(--text); margin-bottom: 24px; display: flex; align-items: center; gap: 12px; }
    .section-subtitle { font-size: 14px; color: var(--muted); margin-bottom: 16px; }
    .form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-bottom: 20px; }
    .form-group { display: flex; flex-direction: column; }
    .form-label { font-weight: 600; color: var(--text); margin-bottom: 8px; font-size: 14px; }
    .form-input { padding: 12px 16px; border: 1px solid var(--border); border-radius: 8px; font-size: 14px; transition: all 0.2s; }
    .form-input:focus { outline: none; border-color: var(--primary); box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1); }
    .required-mark { color: #dc2626; }
    .help-text { font-size: 12px; color: var(--muted); margin-top: 4px; }
    </style>
    
    <div class="admin-header">
        <h1 class="dashboard-title">Professional Client Intake</h1>
        <p class="dashboard-subtitle">Complete verification form for <?=ucfirst(str_replace('_', ' ', $serviceType))?> registration</p>
    </div>
    
    <form method="post" class="intake-form">
        <?=csrf_field()?>
        
        <!-- Client Information -->
        <div class="form-section">
            <h2 class="section-title">
                👤 Client Information
                <span class="section-subtitle">Personal and contact details</span>
            </h2>
            
            <div class="form-grid">
                <div class="form-group">
                    <label class="form-label">Full Legal Name <span class="required-mark">*</span></label>
                    <input type="text" name="full_name" class="form-input" required>
                    <div class="help-text">As appears on government-issued ID</div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Email Address <span class="required-mark">*</span></label>
                    <input type="email" name="email" class="form-input" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Phone Number <span class="required-mark">*</span></label>
                    <input type="tel" name="phone" class="form-input" placeholder="+234XXXXXXXXXX" required>
                    <div class="help-text">Nigerian phone number format</div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Residential Address <span class="required-mark">*</span></label>
                    <input type="text" name="address" class="form-input" required>
                </div>
            </div>
        </div>
        
        <!-- Business Information -->
        <div class="form-section">
            <h2 class="section-title">
                🏢 Business Information
                <span class="section-subtitle">Business details and proposed names</span>
            </h2>
            
            <div class="form-grid">
                <div class="form-group">
                    <label class="form-label">Proposed Business Name 1 <span class="required-mark">*</span></label>
                    <input type="text" name="proposed_name_1" class="form-input" required>
                    <div class="help-text">Primary choice for business name</div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Proposed Business Name 2</label>
                    <input type="text" name="proposed_name_2" class="form-input">
                    <div class="help-text">Alternative choice (optional)</div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Nature of Business <span class="required-mark">*</span></label>
                    <textarea name="nature_of_business" class="form-input" rows="3" required></textarea>
                    <div class="help-text">Detailed description of business activities</div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Business Address <span class="required-mark">*</span></label>
                    <input type="text" name="business_address" class="form-input" required>
                    <div class="help-text">Official business operating address</div>
                </div>
            </div>
        </div>
        
        <!-- Service-Specific Fields -->
        <?php if ($serviceType === 'company'): ?>
        <div class="form-section">
            <h2 class="section-title">
                👥 Shareholder Information
                <span class="section-subtitle">Company structure and ownership</span>
            </h2>
            
            <div class="form-grid">
                <div class="form-group">
                    <label class="form-label">Number of Directors</label>
                    <select name="director_count" class="form-input">
                        <option value="1">1 Director</option>
                        <option value="2">2 Directors</option>
                        <option value="3+">3+ Directors</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Share Capital</label>
                    <select name="share_capital" class="form-input">
                        <option value="1000000">₦1,000,000 (Standard)</option>
                        <option value="5000000">₦5,000,000</option>
                        <option value="10000000">₦10,000,000</option>
                        <option value="custom">Custom Amount</option>
                    </select>
                </div>
            </div>
        </div>
        <?php endif; ?>
        
        <?php if ($serviceType === 'ngo'): ?>
        <div class="form-section">
            <h2 class="section-title">
                🏛️ NGO Information
                <span class="section-subtitle">Trustee and organizational details</span>
            </h2>
            
            <div class="form-grid">
                <div class="form-group">
                    <label class="form-label">Number of Trustees</label>
                    <select name="trustee_count" class="form-input">
                        <option value="2">2 Trustees (Minimum)</option>
                        <option value="3">3 Trustees</option>
                        <option value="4+">4+ Trustees</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label class="form-label">NGO Objectives</label>
                    <textarea name="ngo_objectives" class="form-input" rows="4"></textarea>
                    <div class="help-text">Main objectives and activities of the NGO</div>
                </div>
            </div>
        </div>
        <?php endif; ?>
        
        <div style="display: flex; gap: 16px; justify-content: flex-end; margin-top: 32px;">
            <a href="/customer/dashboard.php" class="btn btn-outline">Cancel</a>
            <button type="submit" class="btn primary">Submit Application</button>
        </div>
    </form>
    
    <?php
    include __DIR__ . '/../includes/footer.php';
    exit;
}

// Invalid step
set_flash('error', 'Invalid step');
redirect('/customer/dashboard.php');
?>
