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

if (!$user) {
    header('Location: /auth/login.php');
    exit;
}

$stmt = db()->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user['id']]);
$userData = $stmt->fetch();

$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $real_name = $_POST['real_name'] ?? '';
    $id_number = $_POST['id_number'] ?? '';
    
    // Handle uploads
    $uploadDir = 'uploads/kyc/';
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
    
    $front = $userData['kyc_photo_front'];
    $back = $userData['kyc_photo_back'];
    $handheld = $userData['kyc_photo_handheld'];
    
    if (isset($_FILES['photo_front']) && $_FILES['photo_front']['error'] === 0) {
        $ext = pathinfo($_FILES['photo_front']['name'], PATHINFO_EXTENSION);
        $front = '/' . $uploadDir . $user['id'] . '_front_' . time() . '.' . $ext;
        move_uploaded_file($_FILES['photo_front']['tmp_name'], ltrim($front, '/'));
    }
    
    if (isset($_FILES['photo_back']) && $_FILES['photo_back']['error'] === 0) {
        $ext = pathinfo($_FILES['photo_back']['name'], PATHINFO_EXTENSION);
        $back = '/' . $uploadDir . $user['id'] . '_back_' . time() . '.' . $ext;
        move_uploaded_file($_FILES['photo_back']['tmp_name'], ltrim($back, '/'));
    }
    
    if (isset($_FILES['photo_handheld']) && $_FILES['photo_handheld']['error'] === 0) {
        $ext = pathinfo($_FILES['photo_handheld']['name'], PATHINFO_EXTENSION);
        $handheld = '/' . $uploadDir . $user['id'] . '_handheld_' . time() . '.' . $ext;
        move_uploaded_file($_FILES['photo_handheld']['tmp_name'], ltrim($handheld, '/'));
    }
    
    if (empty($real_name) || empty($id_number)) {
        $error = __("fill_all_fields");
    } else {
        $stmt = db()->prepare("UPDATE users SET kyc_name = ?, kyc_id_number = ?, kyc_photo_front = ?, kyc_photo_back = ?, kyc_photo_handheld = ?, kyc_status = 1 WHERE id = ?");
        $stmt->execute([$real_name, $id_number, $front, $back, $handheld, $user['id']]);
        $success = __("kyc_submitted");
        // Refresh user data
        $userData['kyc_status'] = 1;
    }
}

$kycStatus = $userData['kyc_status'] ?? 0;
?>

<div class="container py-4">
    <div class="row justify-content-center">
        <div class="col-lg-8">
            <div class="mb-4">
                <a href="/profile.php" class="text-white-50 text-decoration-none d-inline-flex align-items-center gap-2">
                    <i class="bi bi-arrow-left fs-4"></i>
                    <span><?= __('back') ?></span>
                </a>
            </div>

            <div class="card bg-surface border-secondary rounded-4 shadow-lg overflow-hidden">
                <div class="card-header border-secondary bg-black bg-opacity-30 p-4">
                    <h4 class="mb-0 fw-bold d-flex align-items-center gap-3 text-white">
                        <i class="bi bi-person-vcard text-primary"></i>
                        <?= __('kyc') ?>
                    </h4>
                </div>
                
                <div class="card-body p-4 p-md-5">
                    <?php if ($success): ?>
                        <div class="alert alert-success border-0 bg-success bg-opacity-10 text-success rounded-4 mb-4">
                            <i class="bi bi-check-circle-fill me-2"></i><?= $success ?>
                        </div>
                    <?php endif; ?>

                    <?php if ($error): ?>
                        <div class="alert alert-danger border-0 bg-danger bg-opacity-10 text-danger rounded-4 mb-4">
                            <i class="bi bi-exclamation-triangle-fill me-2"></i><?= $error ?>
                        </div>
                    <?php endif; ?>

                    <?php if ($kycStatus == 2): ?>
                        <div class="text-center py-5">
                            <i class="bi bi-patch-check-fill text-success" style="font-size: 80px;"></i>
                            <h3 class="text-white fw-bold mt-4"><?= __('verified') ?></h3>
                            <p class="text-white-50"><?= htmlspecialchars($userData['kyc_name']) ?> (<?= htmlspecialchars($userData['kyc_id_number']) ?>)</p>
                        </div>
                    <?php elseif ($kycStatus == 1): ?>
                        <div class="text-center py-5">
                            <i class="bi bi-clock-history text-warning" style="font-size: 80px;"></i>
                            <h3 class="text-white fw-bold mt-4"><?= __(0) ?></h3>
                            <p class="text-white-50"><?= __('kyc_pending_desc') ?></p>
                        </div>
                    <?php else: ?>
                        <form method="POST" enctype="multipart/form-data">
                            <div class="row g-4 mb-4">
                                <div class="col-md-6">
                                    <label class="form-label text-white-50 small fw-bold mb-2"><?= __('full_name') ?></label>
                                    <input type="text" name="real_name" class="form-control bg-black border-secondary text-white py-3 px-4 rounded-4" placeholder="<?= __('enter_full_name') ?>" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label text-white-50 small fw-bold mb-2"><?= __('id_number') ?></label>
                                    <input type="text" name="id_number" class="form-control bg-black border-secondary text-white py-3 px-4 rounded-4" placeholder="<?= __('enter_id_number') ?>" required>
                                </div>
                            </div>

                            <div class="row g-4 mb-5">
                                <div class="col-md-4">
                                    <label class="form-label text-white-50 small fw-bold mb-2"><?= __('id_front') ?></label>
                                    <div class="upload-area border-secondary rounded-4 p-4 text-center border-dashed position-relative" style="border: 2px dashed #2b3139; cursor: pointer;">
                                        <input type="file" name="photo_front" class="position-absolute w-100 h-100 top-0 start-0 opacity-0" style="cursor: pointer;" required onchange="previewImg(this)">
                                        <div class="preview-content">
                                            <i class="bi bi-image text-white-50 fs-1 mb-2 d-block"></i>
                                            <span class="text-white-50 small"><?= __('upload') ?></span>
                                        </div>
                                        <img class="img-preview d-none w-100 rounded-3 shadow" style="object-fit: cover;">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label text-white-50 small fw-bold mb-2"><?= __('id_back') ?></label>
                                    <div class="upload-area border-secondary rounded-4 p-4 text-center border-dashed position-relative" style="border: 2px dashed #2b3139; cursor: pointer;">
                                        <input type="file" name="photo_back" class="position-absolute w-100 h-100 top-0 start-0 opacity-0" style="cursor: pointer;" required onchange="previewImg(this)">
                                        <div class="preview-content">
                                            <i class="bi bi-image text-white-50 fs-1 mb-2 d-block"></i>
                                            <span class="text-white-50 small"><?= __('upload') ?></span>
                                        </div>
                                        <img class="img-preview d-none w-100 rounded-3 shadow" style="object-fit: cover;">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label text-white-50 small fw-bold mb-2"><?= __('id_handheld') ?></label>
                                    <div class="upload-area border-secondary rounded-4 p-4 text-center border-dashed position-relative" style="border: 2px dashed #2b3139; cursor: pointer;">
                                        <input type="file" name="photo_handheld" class="position-absolute w-100 h-100 top-0 start-0 opacity-0" style="cursor: pointer;" required onchange="previewImg(this)">
                                        <div class="preview-content">
                                            <i class="bi bi-image text-white-50 fs-1 mb-2 d-block"></i>
                                            <span class="text-white-50 small"><?= __('upload') ?></span>
                                        </div>
                                        <img class="img-preview d-none w-100 rounded-3 shadow" style="object-fit: cover;">
                                    </div>
                                </div>
                            </div>

                            <div class="bg-black bg-opacity-20 rounded-4 p-4 mb-5 border border-secondary border-opacity-50">
                                <h6 class="text-white fw-bold mb-3 d-flex align-items-center gap-2">
                                    <i class="bi bi-info-circle text-primary"></i> <?= __('kyc_steps') ?>
                                </h6>
                                <ul class="text-white-50 small mb-0 ps-3">
                                    <li class="mb-2"><?= __('kyc_step1') ?></li>
                                    <li class="mb-2"><?= __('kyc_step2') ?></li>
                                    <li><?= __('kyc_step3') ?></li>
                                </ul>
                            </div>

                            <button type="submit" class="btn btn-primary w-100 py-3 rounded-pill fw-bold shadow-primary">
                                <?= __('submit') ?>
                            </button>
                        </form>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Additional Instructions Section -->
            <div class="card bg-surface border-secondary rounded-4 mt-4">
                <div class="card-body p-4">
                    <h6 class="text-white fw-bold mb-3"><i class="bi bi-shield-check text-success me-2"></i> <?= __('kyc_instructions') ?></h6>
                    <p class="text-white-50 small mb-0">
                        <?= __('kyc_instructions') ?>
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    @media (max-width: 768px) {
        .upload-area { padding: 1.5rem !important; }
        .upload-area i { font-size: 2rem !important; }
        .h4 { font-size: 1.25rem !important; }
        .btn-primary { padding: 12px !important; }
    }
</style>

<script>
function previewImg(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        var parent = input.closest('.upload-area');
        var preview = parent.querySelector('.img-preview');
        var content = parent.querySelector('.preview-content');
        
        reader.onload = function(e) {
            preview.src = e.target.result;
            preview.classList.remove('d-none');
            content.classList.add('d-none');
        }
        
        reader.readAsDataURL(input.files[0]);
    }
}
</script>

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