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

$uid = $_SESSION['user']['id'];
$user = $_SESSION['user'];

// Load existing profile data
$stmt = $pdo->prepare("SELECT * FROM user_profiles WHERE user_id = ?");
$stmt->execute([$uid]);
$profile = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    ensure_csrf();
    
    // Handle file uploads
    $uploadDir = __DIR__ . '/../uploads/profile/' . $uid . '/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    
    $filePaths = [];
    
    // ID Document
    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/' . $uid . '/' . $filename;
        }
    }
    
    // Passport Photo
    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/' . $uid . '/' . $filename;
        }
    }
    
    // Signature
    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/' . $uid . '/' . $filename;
        }
    }
    
    // Build data array
    $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'
    ];
    
    $data = [];
    foreach ($fields as $field) {
        $data[$field] = sanitize_str($_POST[$field] ?? '');
    }
    
    // Add file paths
    foreach ($filePaths as $field => $path) {
        $data[$field] = $path;
    }
    
    // Insert or update
    $columns = array_keys($data);
    $placeholders = array_fill(0, count($columns), '?');
    
    $sql = "INSERT INTO user_profiles (user_id, " . implode(', ', $columns) . ", created_at, updated_at) 
            VALUES (?, " . implode(', ', $placeholders) . ", datetime('now'), datetime('now'))
            ON CONFLICT(user_id) DO UPDATE SET 
            " . implode(', ', array_map(fn($c) => "$c = excluded.$c", $columns)) . ",
            updated_at = datetime('now')";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute(array_merge([$uid], array_values($data)));
    
    // Also update users table for basic info
    $pdo->prepare("UPDATE users SET full_name = ?, email = ?, phone = ? WHERE id = ?")
        ->execute([$data['full_name'], $data['email'], $data['phone'], $uid]);
    
    // Update session
    $_SESSION['user']['full_name'] = $data['full_name'];
    $_SESSION['user']['email'] = $data['email'];
    $_SESSION['user']['phone'] = $data['phone'];
    
    $_SESSION['profile_success'] = 'Your profile has been updated successfully!';
    redirect('/customer/profile.php');
}

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

<style>
.edit-profile-container { max-width: 900px; margin: 40px auto; padding: 0 20px; }
.edit-profile-header { margin-bottom: 32px; }
.edit-profile-header h1 { margin: 0 0 8px 0; font-size: 24px; font-weight: 700; color: #1f2937; }
.edit-profile-header p { margin: 0; color: #6b7280; font-size: 14px; }

.form-section { background: white; border: 1px solid #e5e7eb; border-radius: 16px; padding: 24px; margin-bottom: 24px; }
.form-section h3 { margin: 0 0 20px 0; font-size: 16px; font-weight: 600; color: #374151; padding-bottom: 12px; border-bottom: 2px solid #e5e7eb; }

.form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 16px; }
.form-group { margin-bottom: 0; }
.form-group.full-width { grid-column: 1 / -1; }
.form-group label { display: block; font-weight: 500; color: #374151; margin-bottom: 6px; font-size: 13px; }
.form-group input, .form-group select, .form-group textarea { width: 100%; padding: 10px 14px; border: 2px solid #e5e7eb; border-radius: 8px; font-size: 14px; transition: border-color 0.2s; }
.form-group input:focus, .form-group select:focus, .form-group textarea:focus { outline: none; border-color: #10b981; }
.form-group textarea { resize: vertical; }

.file-upload-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-top: 16px; }
.file-upload-box { border: 2px dashed #e5e7eb; border-radius: 10px; padding: 16px; text-align: center; transition: all 0.2s; }
.file-upload-box:hover { border-color: #10b981; background: #f0fdf4; }
.file-upload-box.has-file { border-style: solid; border-color: #10b981; background: #f0fdf4; }
.file-upload-box input[type="file"] { display: none; }
.file-upload-label { cursor: pointer; display: block; }
.file-icon { font-size: 24px; margin-bottom: 8px; }
.file-label-strong { font-weight: 600; color: #374151; font-size: 13px; margin-bottom: 4px; }
.file-label-text { font-size: 12px; color: #6b7280; }
.file-current { margin-top: 8px; padding: 8px; background: white; border-radius: 6px; font-size: 12px; }
.file-current a { color: #10b981; text-decoration: none; }

.btn { display: inline-flex; align-items: center; gap: 8px; padding: 12px 28px; border-radius: 10px; font-weight: 600; font-size: 14px; text-decoration: none; transition: all 0.2s; border: none; cursor: pointer; }
.btn-primary { background: #10b981; color: white; }
.btn-primary:hover { background: #059669; }
.btn-secondary { background: #f3f4f6; color: #374151; }
.btn-secondary:hover { background: #e5e7eb; }

.button-group { display: flex; gap: 16px; justify-content: flex-end; margin-top: 32px; padding-top: 24px; border-top: 1px solid #e5e7eb; }

.info-note { background: #eff6ff; border-left: 4px solid #3b82f6; padding: 12px 16px; margin-bottom: 24px; border-radius: 0 8px 8px 0; font-size: 13px; color: #1e40af; }
</style>

<div class="edit-profile-container">
    <div class="edit-profile-header">
        <h1>Edit Your Profile</h1>
        <p>Update your personal information. These details will be used to pre-fill future applications.</p>
    </div>

    <div class="info-note">
        💡 <strong>Tip:</strong> Completing your profile saves time on future applications. All information you provide here will be automatically filled in when you start a new service application.
    </div>

    <form method="POST" enctype="multipart/form-data">
        <?= csrf_field() ?>

        <!-- Personal Information -->
        <div class="form-section">
            <h3>👤 Personal Information</h3>
            <div class="form-grid">
                <div class="form-group">
                    <label>Full Name *</label>
                    <input type="text" name="full_name" value="<?= e($profile['full_name'] ?? $user['full_name']) ?>" required>
                </div>
                <div class="form-group">
                    <label>Email Address *</label>
                    <input type="email" name="email" value="<?= e($profile['email'] ?? $user['email']) ?>" required>
                </div>
                <div class="form-group">
                    <label>Phone Number *</label>
                    <input type="tel" name="phone" value="<?= e($profile['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="<?= e($profile['date_of_birth'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label>Nationality</label>
                    <input type="text" name="nationality" value="<?= e($profile['nationality'] ?? 'Nigerian') ?>">
                </div>
                <div class="form-group">
                    <label>Gender</label>
                    <select name="gender">
                        <option value="">Select...</option>
                        <option value="Male" <?= ($profile['gender'] ?? '') === 'Male' ? 'selected' : '' ?>>Male</option>
                        <option value="Female" <?= ($profile['gender'] ?? '') === 'Female' ? 'selected' : '' ?>>Female</option>
                        <option value="Other" <?= ($profile['gender'] ?? '') === 'Other' ? 'selected' : '' ?>>Other</option>
                    </select>
                </div>
            </div>
        </div>

        <!-- Address Information -->
        <div class="form-section">
            <h3>📍 Address Information</h3>
            <div class="form-grid">
                <div class="form-group full-width">
                    <label>Residential Address</label>
                    <textarea name="residential_address" rows="2" placeholder="Full residential address"><?= e($profile['residential_address'] ?? '') ?></textarea>
                </div>
                <div class="form-group">
                    <label>City</label>
                    <input type="text" name="city" value="<?= e($profile['city'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label>State</label>
                    <input type="text" name="state" value="<?= e($profile['state'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label>Country</label>
                    <input type="text" name="country" value="<?= e($profile['country'] ?? 'Nigeria') ?>">
                </div>
            </div>
        </div>

        <!-- Business Information -->
        <div class="form-section">
            <h3>🏢 Business Information</h3>
            <div class="form-grid">
                <div class="form-group">
                    <label>Business Name (if applicable)</label>
                    <input type="text" name="business_name" value="<?= e($profile['business_name'] ?? '') ?>" placeholder="Existing business name">
                </div>
                <div class="form-group full-width">
                    <label>Business Address</label>
                    <textarea name="business_address" rows="2" placeholder="Business/office address"><?= e($profile['business_address'] ?? '') ?></textarea>
                </div>
                <div class="form-group full-width">
                    <label>Nature of Business</label>
                    <textarea name="nature_of_business" rows="2" placeholder="Describe what your business does"><?= e($profile['nature_of_business'] ?? '') ?></textarea>
                </div>
            </div>
        </div>

        <!-- Identity Documents -->
        <div class="form-section">
            <h3>🪪 Identity Documents</h3>
            <div class="form-grid">
                <div class="form-group">
                    <label>ID Type</label>
                    <select name="id_type">
                        <option value="">Select ID Type...</option>
                        <option value="NIN" <?= ($profile['id_type'] ?? '') === 'NIN' ? 'selected' : '' ?>>National ID (NIN)</option>
                        <option value="Passport" <?= ($profile['id_type'] ?? '') === 'Passport' ? 'selected' : '' ?>>International Passport</option>
                        <option value="Voters Card" <?= ($profile['id_type'] ?? '') === 'Voters Card' ? 'selected' : '' ?>>Voter's Card</option>
                        <option value="Drivers License" <?= ($profile['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="<?= e($profile['id_number'] ?? '') ?>" placeholder="Enter ID number">
                </div>
            </div>

            <div class="file-upload-row">
                <div class="file-upload-box <?= !empty($profile['id_document_path']) ? 'has-file' : '' ?>">
                    <label class="file-upload-label">
                        <input type="file" name="id_document" accept=".pdf,.jpg,.jpeg,.png" onchange="updateFileLabel(this, 'id-doc-label')">
                        <div class="file-icon">📄</div>
                        <div class="file-label-strong" id="id-doc-label">ID Document</div>
                        <div class="file-label-text">PDF, JPG, PNG (Max 5MB)</div>
                    </label>
                    <?php if (!empty($profile['id_document_path'])): ?>
                    <div class="file-current">
                        ✓ Current: <a href="<?= e($profile['id_document_path']) ?>" target="_blank">View</a>
                    </div>
                    <?php endif; ?>
                </div>
                <div class="file-upload-box <?= !empty($profile['passport_path']) ? 'has-file' : '' ?>">
                    <label class="file-upload-label">
                        <input type="file" name="passport_photo" accept=".jpg,.jpeg,.png" onchange="updateFileLabel(this, 'passport-label')">
                        <div class="file-icon">📷</div>
                        <div class="file-label-strong" id="passport-label">Passport Photo</div>
                        <div class="file-label-text">JPG, PNG (Max 2MB)</div>
                    </label>
                    <?php if (!empty($profile['passport_path'])): ?>
                    <div class="file-current">
                        ✓ Current: <a href="<?= e($profile['passport_path']) ?>" target="_blank">View</a>
                    </div>
                    <?php endif; ?>
                </div>
                <div class="file-upload-box <?= !empty($profile['signature_path']) ? 'has-file' : '' ?>">
                    <label class="file-upload-label">
                        <input type="file" name="signature" accept=".jpg,.jpeg,.png" onchange="updateFileLabel(this, 'sig-label')">
                        <div class="file-icon">✍️</div>
                        <div class="file-label-strong" id="sig-label">Signature</div>
                        <div class="file-label-text">JPG, PNG (Max 2MB)</div>
                    </label>
                    <?php if (!empty($profile['signature_path'])): ?>
                    <div class="file-current">
                        ✓ Current: <a href="<?= e($profile['signature_path']) ?>" target="_blank">View</a>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Next of Kin -->
        <div class="form-section">
            <h3>👥 Next of Kin</h3>
            <div class="form-grid">
                <div class="form-group">
                    <label>Full Name</label>
                    <input type="text" name="next_of_kin_name" value="<?= e($profile['next_of_kin_name'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label>Phone Number</label>
                    <input type="tel" name="next_of_kin_phone" value="<?= e($profile['next_of_kin_phone'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label>Relationship</label>
                    <input type="text" name="next_of_kin_relationship" value="<?= e($profile['next_of_kin_relationship'] ?? '') ?>" placeholder="e.g., Spouse, Parent, Sibling">
                </div>
            </div>
        </div>

        <div class="button-group">
            <a href="/customer/profile.php" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">💾 Save Changes</button>
        </div>
    </form>
</div>

<script>
function updateFileLabel(input, labelId) {
    const label = document.getElementById(labelId);
    if (input.files && input.files[0]) {
        label.textContent = input.files[0].name;
        label.style.color = '#059669';
        input.closest('.file-upload-box').classList.add('has-file');
    }
}
</script>

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