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

// Handle form submission and create application
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['proceed_to_payment'])) {
    $pdo = require __DIR__ . '/../config/database.php';
    
    try {
        // Start transaction
        $pdo->beginTransaction();
        
        // Create service application
        $stmt = $pdo->prepare("
            INSERT INTO service_applications (
                user_id, application_id, service_type, universal_info, 
                service_specific, files, status, created_at, updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, 'pending', NOW(), NOW())
        ");
        
        $applicationId = 'SRV' . date('Y') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
        $formData = $_SESSION['master_service_form'];
        
        $stmt->execute([
            $_SESSION['user']['id'],
            $applicationId,
            $formData['service_type'],
            json_encode($formData['universal_info']),
            json_encode($formData['service_specific']),
            json_encode($formData['files'])
        ]);
        
        $serviceId = $pdo->lastInsertId();
        
        // Handle file uploads
        if (!empty($_SESSION['master_service_form']['files'])) {
            $fileStmt = $pdo->prepare("
                INSERT INTO service_files (
                    application_id, file_type, filename, original_name, 
                    file_size, mime_type, upload_date
                ) VALUES (?, ?, ?, ?, ?, ?, NOW())
            ");
            
            foreach ($_SESSION['master_service_form']['files'] as $fieldName => $file) {
                $fileStmt->execute([
                    $serviceId,
                    $fieldName,
                    $file['filename'],
                    $file['original_name'],
                    $file['size'],
                    $file['type']
                ]);
            }
        }
        
        // Create payment record
        $paymentStmt = $pdo->prepare("
            INSERT INTO payments (
                user_id, application_id, application_type, amount, 
                currency, status, payment_method, created_at
            ) VALUES (?, ?, ?, ?, 'NGN', 'pending', 'online', NOW())
        ");
        
        $paymentAmount = getServicePrice($formData['service_type']);
        $paymentStmt->execute([
            $_SESSION['user']['id'],
            $serviceId,
            'service',
            $paymentAmount
        ]);
        
        $paymentId = $pdo->lastInsertId();
        
        // Create client folder structure
        $clientId = 'CL' . str_pad($_SESSION['user']['id'], 4, '0', STR_PAD_LEFT);
        $serviceType = $formData['service_type'];
        $clientBasePath = __DIR__ . "/../uploads/clients/{$clientId}/{$serviceType}";
        
        if (!is_dir(__DIR__ . "/../uploads/clients/{$clientId}")) {
            mkdir(__DIR__ . "/../uploads/clients/{$clientId}", 0755, true);
        }
        if (!is_dir($clientBasePath)) {
            mkdir($clientBasePath, 0755, true);
        }
        mkdir($clientBasePath . '/Documents', 0755, true);
        mkdir($clientBasePath . '/Certificates', 0755, true);
        
        // Move uploaded files to client folder
        if (!empty($_SESSION['master_service_form']['files'])) {
            foreach ($_SESSION['master_service_form']['files'] as $file) {
                $sourcePath = __DIR__ . "/../uploads/services/{$file['filename']}";
                $destPath = $clientBasePath . '/Documents/' . $file['filename'];
                if (file_exists($sourcePath)) {
                    rename($sourcePath, $destPath);
                }
            }
        }
        
        // Commit transaction
        $pdo->commit();
        
        // Clear session data
        unset($_SESSION['master_service_form']);
        
        // Redirect to payment
        header("Location: /customer/payment.php?payment_id=$paymentId&application_id=$serviceId");
        exit;
        
    } catch (Exception $e) {
        $pdo->rollBack();
        error_log("Service application error: " . $e->getMessage());
        $error = "Failed to create application. Please try again.";
    }
}

// Handle save for later
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_later'])) {
    $pdo = require __DIR__ . '/../config/database.php';
    
    try {
        $stmt = $pdo->prepare("
            INSERT INTO saved_applications (
                user_id, application_type, form_data, status, created_at
            ) VALUES (?, 'service', ?, 'saved', NOW())
            ON DUPLICATE KEY UPDATE 
            form_data = VALUES(form_data), updated_at = NOW()
        ");
        
        $stmt->execute([
            $_SESSION['user']['id'],
            json_encode($_SESSION['master_service_form'])
        ]);
        
        $success = "Application saved successfully. You can continue later from your dashboard.";
        
    } catch (Exception $e) {
        error_log("Save application error: " . $e->getMessage());
        $error = "Failed to save application. Please try again.";
    }
}

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

<div class="container" style="max-width: 1200px; margin: 0 auto; padding: 40px 20px;">
    <h1 style="font-size: 32px; font-weight: 700; margin-bottom: 16px;">Service Applications</h1>
    <p style="font-size: 18px; color: #64748b; margin-bottom: 40px;">Track and manage your service applications</p>
    
    <?php if (isset($success)): ?>
        <div class="flash success"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>
    
    <?php if (isset($error)): ?>
        <div class="flash error"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>
    
    <!-- Start New Application Button -->
    <div style="text-align: center; margin-bottom: 40px;">
        <a href="/customer/master-service.php?step=1" class="btn primary" style="font-size: 18px; padding: 16px 32px;">
            📋 Start New Service Application
        </a>
    </div>
    
    <!-- Applications List -->
    <div class="applications-grid">
        <?php
        $pdo = require __DIR__ . '/../config/database.php';
        
        // Get active applications
        $stmt = $pdo->prepare("
            SELECT sa.*, p.status as payment_status, p.amount as payment_amount
            FROM service_applications sa
            LEFT JOIN payments p ON sa.id = p.application_id AND p.application_type = 'service'
            WHERE sa.user_id = ? 
            ORDER BY sa.created_at DESC
        ");
        
        $stmt->execute([$_SESSION['user']['id']]);
        $applications = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (empty($applications)):
        ?>
        <div style="text-align: center; padding: 60px 20px; background: #f8fafc; border-radius: 12px; border: 1px solid #e5e7eb;">
            <div style="font-size: 48px; margin-bottom: 16px;">📋</div>
            <h3 style="font-size: 24px; margin-bottom: 8px;">No Service Applications Yet</h3>
            <p style="color: #64748b; margin-bottom: 24px;">Start your first service application to register your business or protect your brand.</p>
            <a href="/customer/master-service.php?step=1" class="btn primary">
                Create Your First Application
            </a>
        </div>
        <?php else: ?>
        
        <?php foreach ($applications as $app): ?>
        <div class="application-card">
            <div class="application-header">
                <div>
                    <h3><?= htmlspecialchars($app['application_id']) ?></h3>
                    <p class="application-name"><?= getServiceTitle($app['service_type']) ?></p>
                </div>
                <div class="application-status">
                    <span class="status-badge status-<?= $app['status'] ?>">
                        <?= getStatusLabel($app['status']) ?>
                    </span>
                </div>
            </div>
            
            <div class="application-details">
                <div class="detail-row">
                    <span class="detail-label">Service Type:</span>
                    <span class="detail-value"><?= getServiceTitle($app['service_type']) ?></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Client Name:</span>
                    <span class="detail-value"><?= getClientName($app['universal_info']) ?></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Submitted:</span>
                    <span class="detail-value"><?= date('M j, Y', strtotime($app['created_at'])) ?></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Amount:</span>
                    <span class="detail-value">₦<?= number_format($app['payment_amount'] ?? getServicePrice($app['service_type'])) ?></span>
                </div>
            </div>
            
            <!-- Progress Timeline -->
            <div class="progress-timeline">
                <h4>Application Progress</h4>
                <div class="timeline">
                    <?php
                    $timelineSteps = [
                        'pending' => 'Order Received',
                        'documents_verified' => 'Documents Verified',
                        'application_submitted' => 'Application Submitted',
                        'under_review' => 'Under Review',
                        'query_from_cac' => 'Query from CAC',
                        'approved' => 'Approved',
                        'certificate_delivered' => 'Certificate Delivered'
                    ];
                    
                    $currentStepIndex = array_search($app['status'], array_keys($timelineSteps));
                    
                    foreach ($timelineSteps as $step => $label):
                        $stepIndex = array_search($step, array_keys($timelineSteps));
                        $isCompleted = $stepIndex < $currentStepIndex;
                        $isCurrent = $stepIndex === $currentStepIndex;
                    ?>
                    <div class="timeline-item <?= $isCompleted ? 'completed' : '' ?> <?= $isCurrent ? 'current' : '' ?>">
                        <div class="timeline-dot"></div>
                        <div class="timeline-content">
                            <div class="timeline-label"><?= $label ?></div>
                            <?php if ($isCompleted): ?>
                                <div class="timeline-check">✓</div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            
            <div class="application-actions">
                <a href="/customer/service-details.php?id=<?= $app['id'] ?>" class="btn secondary">View Details</a>
                <?php if ($app['payment_status'] === 'pending'): ?>
                    <a href="/customer/payment.php?application_id=<?= $app['id'] ?>" class="btn primary">Complete Payment</a>
                <?php endif; ?>
                <?php if ($app['status'] === 'certificate_delivered'): ?>
                    <a href="/customer/download-certificate.php?id=<?= $app['id'] ?>" class="btn primary">Download Certificate</a>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
        
        <?php endif; ?>
    </div>
</div>

<style>
.applications-grid {
    display: grid;
    gap: 24px;
}

.application-card {
    background: white;
    border: 1px solid #e5e7eb;
    border-radius: 16px;
    padding: 24px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
    transition: all 0.2s ease;
}

.application-card:hover {
    box-shadow: 0 8px 12px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
}

.application-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20px;
}

.application-header h3 {
    font-size: 20px;
    font-weight: 700;
    color: #1f2937;
    margin-bottom: 4px;
}

.application-name {
    color: #64748b;
    font-size: 16px;
    margin: 0;
}

.status-badge {
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    text-transform: uppercase;
}

.status-pending { background: #fef3c7; color: #92400e; }
.status-documents_verified { background: #dbeafe; color: #1e40af; }
.status-application_submitted { background: #e9d5ff; color: #6b21a8; }
.status-under_review { background: #fed7aa; color: #9a3412; }
.status-query_from_cac { background: #fef2f2; color: #dc2626; }
.status-approved { background: #d1fae5; color: #065f46; }
.status-certificate_delivered { background: #d1fae5; color: #065f46; }

.application-details {
    display: grid;
    gap: 12px;
    margin-bottom: 24px;
}

.detail-row {
    display: flex;
    justify-content: space-between;
    padding: 8px 0;
    border-bottom: 1px solid #f3f4f6;
}

.detail-label {
    font-weight: 600;
    color: #374151;
}

.detail-value {
    color: #64748b;
}

.progress-timeline {
    margin-bottom: 24px;
}

.progress-timeline h4 {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 16px;
    color: #1f2937;
}

.timeline {
    position: relative;
    padding-left: 30px;
}

.timeline::before {
    content: '';
    position: absolute;
    left: 15px;
    top: 0;
    bottom: 0;
    width: 2px;
    background: #e5e7eb;
}

.timeline-item {
    position: relative;
    margin-bottom: 20px;
}

.timeline-dot {
    position: absolute;
    left: -23px;
    top: 6px;
    width: 12px;
    height: 12px;
    border-radius: 50%;
    background: white;
    border: 2px solid #e5e7eb;
    z-index: 2;
}

.timeline-item.completed .timeline-dot {
    background: var(--primary);
    border-color: var(--primary);
}

.timeline-item.current .timeline-dot {
    background: var(--primary);
    border-color: var(--primary);
    box-shadow: 0 0 0 4px rgba(16, 185, 129, 0.2);
}

.timeline-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.timeline-label {
    font-size: 14px;
    color: #64748b;
}

.timeline-check {
    color: var(--primary);
    font-weight: 600;
}

.application-actions {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
}

@media (max-width: 768px) {
    .applications-grid {
        gap: 16px;
    }
    
    .application-card {
        padding: 16px;
    }
    
    .application-header {
        flex-direction: column;
        gap: 12px;
    }
    
    .timeline-content {
        flex-direction: column;
        align-items: flex-start;
        gap: 4px;
    }
    
    .application-actions {
        flex-direction: column;
    }
}
</style>

<?php
function getServiceTitle(string $serviceType): string {
    $titles = [
        'business_name' => 'Business Name Registration',
        'limited_company' => 'Limited Company Registration',
        'ngo' => 'NGO / Incorporated Trustee',
        'trademark' => 'Trademark Registration',
        'scuml' => 'SCUML Registration',
        'tin' => 'Tax Identification Number (TIN)',
        'post_incorporation' => 'Post-Incorporation Services'
    ];
    
    return $titles[$serviceType] ?? $serviceType;
}

function getStatusLabel(string $status): string {
    $labels = [
        'pending' => 'Order Received',
        'documents_verified' => 'Documents Verified',
        'application_submitted' => 'Application Submitted',
        'under_review' => 'Under Review',
        'query_from_cac' => 'Query from CAC',
        'approved' => 'Approved',
        'certificate_delivered' => 'Certificate Delivered'
    ];
    
    return $labels[$status] ?? $status;
}

function getClientName(string $universalInfoJson): string {
    $universalInfo = json_decode($universalInfoJson, true);
    return $universalInfo['full_name'] ?? 'Unknown';
}

function getServicePrice(string $serviceType): int {
    $prices = [
        'business_name' => 50000,
        'limited_company' => 100000,
        'ngo' => 80000,
        'trademark' => 100000,
        'scuml' => 30000,
        'tin' => 25000,
        'post_incorporation' => 40000
    ];
    
    return $prices[$serviceType] ?? 50000;
}

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