<?php
require_once __DIR__ . '/../../includes/init.php';
middleware(['mr']);

$db  = getDBConnection();
$uid = (int)getSession('user_id');

// Auto-create table
try {
    $db->exec("CREATE TABLE IF NOT EXISTS mr_kyc (
        id              INT AUTO_INCREMENT PRIMARY KEY,
        user_id         INT NOT NULL,
        full_name       VARCHAR(255) DEFAULT NULL,
        mobile          VARCHAR(20)  DEFAULT NULL,
        current_address TEXT         DEFAULT NULL,
        aadhaar_number  VARCHAR(20)  DEFAULT NULL,
        aadhaar_front   VARCHAR(255) DEFAULT NULL,
        aadhaar_back    VARCHAR(255) DEFAULT NULL,
        aadhaar_address TEXT         DEFAULT NULL,
        bank_account    VARCHAR(50)  DEFAULT NULL,
        bank_ifsc       VARCHAR(20)  DEFAULT NULL,
        passbook_image  VARCHAR(255) DEFAULT NULL,
        pf_number       VARCHAR(50)  DEFAULT NULL,
        esi_number      VARCHAR(50)  DEFAULT NULL,
        pan_number      VARCHAR(20)  DEFAULT NULL,
        pan_image       VARCHAR(255) DEFAULT NULL,
        submitted_at    TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at      TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_user (user_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch (PDOException $e) {}

$kyc     = dbRow($db, "SELECT * FROM mr_kyc WHERE user_id=?", [$uid]);
if (!$kyc) $kyc = array();

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

// ── Image upload helper ───────────────────────────────────────
function saveKycImage(array $file, string $folder) {
    $allowed = array('image/jpeg','image/jpg','image/png','image/webp');
    if (!in_array($file['type'], $allowed)) return false;
    if ($file['size'] > 5 * 1024 * 1024) return false;
    $dir = UPLOAD_PATH . $folder . DIRECTORY_SEPARATOR;
    if (!is_dir($dir)) mkdir($dir, 0755, true);
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, array('jpg','jpeg','png','webp'))) $ext = 'jpg';
    $filename = date('Ymd_His') . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
    if (!move_uploaded_file($file['tmp_name'], $dir . $filename)) return false;
    return $folder . '/' . $filename;
}

// ── POST handler ──────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!validateCsrfToken($_POST['csrf_token'] ?? '')) {
        $error = 'Invalid request. Please refresh and try again.';
    } else {
        $data = array(
            'full_name'       => trim($_POST['full_name']       ?? ''),
            'mobile'          => preg_replace('/\D/', '', $_POST['mobile'] ?? ''),
            'current_address' => trim($_POST['current_address'] ?? ''),
            'aadhaar_number'  => preg_replace('/\D/', '', $_POST['aadhaar_number'] ?? ''),
            'aadhaar_address' => trim($_POST['aadhaar_address'] ?? ''),
            'bank_account'    => trim($_POST['bank_account']    ?? ''),
            'bank_ifsc'       => strtoupper(trim($_POST['bank_ifsc'] ?? '')),
            'pf_number'       => trim($_POST['pf_number']       ?? ''),
            'esi_number'      => trim($_POST['esi_number']      ?? ''),
            'pan_number'      => strtoupper(trim($_POST['pan_number'] ?? '')),
        );

        // Image fields
        foreach (array('aadhaar_front','aadhaar_back','passbook_image','pan_image') as $field) {
            if (!empty($_FILES[$field]['tmp_name']) && $_FILES[$field]['error'] === UPLOAD_ERR_OK) {
                $saved = saveKycImage($_FILES[$field], 'kyc');
                if ($saved) {
                    if (!empty($kyc[$field])) @unlink(UPLOAD_PATH . $kyc[$field]);
                    $data[$field] = $saved;
                } else {
                    $error = 'Image upload failed (' . $field . '). Use JPG/PNG, max 5MB.';
                    break;
                }
            } elseif (!empty($kyc[$field])) {
                $data[$field] = $kyc[$field];
            } else {
                $data[$field] = null;
            }
        }

        if (!$error) {
            try {
                if ($kyc) {
                    $sets = array();
                    foreach (array_keys($data) as $k) $sets[] = "$k = ?";
                    $vals = array_values($data);
                    $vals[] = $uid;
                    $db->prepare("UPDATE mr_kyc SET " . implode(', ', $sets) . ", updated_at = NOW() WHERE user_id = ?")
                       ->execute($vals);
                } else {
                    $keys = implode(', ', array_keys($data));
                    $phs  = implode(', ', array_fill(0, count($data), '?'));
                    $vals = array_values($data);
                    $vals[] = $uid;
                    $db->prepare("INSERT INTO mr_kyc ($keys, user_id) VALUES ($phs, ?)")->execute($vals);
                }
                $success = 'KYC details saved successfully!';
                $kyc = dbRow($db, "SELECT * FROM mr_kyc WHERE user_id=?", [$uid]);
                if (!$kyc) $kyc = array();
            } catch (PDOException $e) {
                $error = 'Save failed. Please try again.';
            }
        }
    }
}

function kv($kyc, $key) { return h($kyc[$key] ?? ''); }

$pageTitle = 'My KYC Details';
include __DIR__ . '/../../includes/header.php';
?>

<div class="page-header">
    <div>
        <h1><i class="bi bi-person-vcard-fill me-2 text-primary"></i>My KYC Details</h1>
        <nav aria-label="breadcrumb"><ol class="breadcrumb mb-0" style="font-size:.8rem;">
            <li class="breadcrumb-item"><a href="<?= BASE_URL ?>/modules/dashboard/index.php">Dashboard</a></li>
            <li class="breadcrumb-item active">KYC Details</li>
        </ol></nav>
    </div>
    <?php if ($kyc): ?>
    <span class="badge bg-success p-2"><i class="bi bi-check-circle me-1"></i>Submitted</span>
    <?php else: ?>
    <span class="badge bg-warning text-dark p-2"><i class="bi bi-exclamation-circle me-1"></i>Not Submitted</span>
    <?php endif; ?>
</div>

<?php if ($success): ?>
<div class="alert alert-success d-flex align-items-center gap-2">
    <i class="bi bi-check-circle-fill"></i><?= h($success) ?>
</div>
<?php endif; ?>
<?php if ($error): ?>
<div class="alert alert-danger d-flex align-items-center gap-2">
    <i class="bi bi-exclamation-circle-fill"></i><?= h($error) ?>
</div>
<?php endif; ?>

<form method="POST" enctype="multipart/form-data" id="kycForm" novalidate>
    <input type="hidden" name="csrf_token" value="<?= generateCsrfToken() ?>">

    <!-- ── 1. Basic Details ──────────────────────────────────── -->
    <div class="erp-card mb-3">
        <h6 class="fw-bold mb-3 d-flex align-items-center gap-2">
            <span class="step-badge">1</span>
            <i class="bi bi-person-fill text-primary"></i> Basic Details
        </h6>
        <div class="mb-3">
            <label class="form-label">Full Name <span class="text-danger">*</span></label>
            <input type="text" name="full_name" class="form-control"
                   value="<?= kv($kyc,'full_name') ?>" placeholder="Enter full name" required>
        </div>
        <div class="mb-3">
            <label class="form-label">Mobile Number <span class="text-danger">*</span></label>
            <input type="tel" name="mobile" class="form-control"
                   value="<?= kv($kyc,'mobile') ?>" placeholder="10-digit mobile number"
                   maxlength="10" inputmode="numeric" required>
        </div>
        <div class="mb-0">
            <label class="form-label">Current Address <span class="text-danger">*</span></label>
            <textarea name="current_address" class="form-control" rows="2"
                      placeholder="Current residential address" required><?= kv($kyc,'current_address') ?></textarea>
        </div>
    </div>

    <!-- ── 2. Aadhaar Details ───────────────────────────────── -->
    <div class="erp-card mb-3">
        <h6 class="fw-bold mb-3 d-flex align-items-center gap-2">
            <span class="step-badge">2</span>
            <i class="bi bi-card-heading text-info"></i> Aadhaar Details
        </h6>
        <div class="mb-3">
            <label class="form-label">Aadhaar Number</label>
            <input type="text" name="aadhaar_number" class="form-control"
                   value="<?= kv($kyc,'aadhaar_number') ?>" placeholder="12-digit Aadhaar number"
                   maxlength="12" inputmode="numeric">
        </div>
        <div class="row g-3 mb-3">
            <div class="col-6">
                <label class="form-label">Aadhaar Front Photo</label>
                <?php if (!empty($kyc['aadhaar_front'])): ?>
                <div class="mb-1">
                    <a href="<?= imgUrl($kyc['aadhaar_front']) ?>" target="_blank">
                        <img src="<?= imgUrl($kyc['aadhaar_front']) ?>" class="img-fluid rounded" style="max-height:80px;object-fit:cover;">
                    </a>
                </div>
                <?php endif; ?>
                <input type="file" name="aadhaar_front" class="form-control" accept="image/*"
                       id="file_aadhaar_front" onchange="previewImg(this,'prev_af')">
                <img id="prev_af" src="" class="img-fluid rounded mt-1 d-none" style="max-height:70px;">
            </div>
            <div class="col-6">
                <label class="form-label">Aadhaar Back Photo</label>
                <?php if (!empty($kyc['aadhaar_back'])): ?>
                <div class="mb-1">
                    <a href="<?= imgUrl($kyc['aadhaar_back']) ?>" target="_blank">
                        <img src="<?= imgUrl($kyc['aadhaar_back']) ?>" class="img-fluid rounded" style="max-height:80px;object-fit:cover;">
                    </a>
                </div>
                <?php endif; ?>
                <input type="file" name="aadhaar_back" class="form-control" accept="image/*"
                       id="file_aadhaar_back" onchange="previewImg(this,'prev_ab')">
                <img id="prev_ab" src="" class="img-fluid rounded mt-1 d-none" style="max-height:70px;">
            </div>
        </div>
        <div class="mb-0">
            <label class="form-label">Address as per Aadhaar</label>
            <textarea name="aadhaar_address" class="form-control" rows="2"
                      placeholder="Address printed on Aadhaar card"><?= kv($kyc,'aadhaar_address') ?></textarea>
        </div>
    </div>

    <!-- ── 3. Bank Details ──────────────────────────────────── -->
    <div class="erp-card mb-3">
        <h6 class="fw-bold mb-3 d-flex align-items-center gap-2">
            <span class="step-badge">3</span>
            <i class="bi bi-bank text-success"></i> Bank Details
        </h6>
        <div class="mb-3">
            <label class="form-label">Account Number</label>
            <input type="text" name="bank_account" class="form-control"
                   value="<?= kv($kyc,'bank_account') ?>" placeholder="Bank account number" inputmode="numeric">
        </div>
        <div class="mb-3">
            <label class="form-label">IFSC Code</label>
            <input type="text" name="bank_ifsc" class="form-control"
                   value="<?= kv($kyc,'bank_ifsc') ?>" placeholder="e.g. SBIN0001234" maxlength="11"
                   style="text-transform:uppercase;">
        </div>
        <div class="mb-0">
            <label class="form-label">Passbook Photo (clear photo)</label>
            <?php if (!empty($kyc['passbook_image'])): ?>
            <div class="mb-1">
                <a href="<?= imgUrl($kyc['passbook_image']) ?>" target="_blank">
                    <img src="<?= imgUrl($kyc['passbook_image']) ?>" class="img-fluid rounded" style="max-height:80px;object-fit:cover;">
                </a>
            </div>
            <?php endif; ?>
            <input type="file" name="passbook_image" class="form-control" accept="image/*"
                   onchange="previewImg(this,'prev_pb')">
            <img id="prev_pb" src="" class="img-fluid rounded mt-1 d-none" style="max-height:70px;">
        </div>
    </div>

    <!-- ── 4. Employment / Social Security ─────────────────── -->
    <div class="erp-card mb-3">
        <h6 class="fw-bold mb-3 d-flex align-items-center gap-2">
            <span class="step-badge">4</span>
            <i class="bi bi-briefcase-fill text-warning"></i> Employment Details
        </h6>
        <div class="mb-3">
            <label class="form-label">PF Number (Provident Fund)</label>
            <input type="text" name="pf_number" class="form-control"
                   value="<?= kv($kyc,'pf_number') ?>" placeholder="PF account number">
        </div>
        <div class="mb-0">
            <label class="form-label">ESI Number</label>
            <input type="text" name="esi_number" class="form-control"
                   value="<?= kv($kyc,'esi_number') ?>" placeholder="ESI number" inputmode="numeric">
        </div>
    </div>

    <!-- ── 5. PAN Details ───────────────────────────────────── -->
    <div class="erp-card mb-3">
        <h6 class="fw-bold mb-3 d-flex align-items-center gap-2">
            <span class="step-badge">5</span>
            <i class="bi bi-credit-card-2-front-fill text-danger"></i> PAN Details
        </h6>
        <div class="mb-3">
            <label class="form-label">PAN Card Number</label>
            <input type="text" name="pan_number" class="form-control"
                   value="<?= kv($kyc,'pan_number') ?>" placeholder="e.g. ABCDE1234F"
                   maxlength="10" style="text-transform:uppercase;">
        </div>
        <div class="mb-0">
            <label class="form-label">PAN Card Photo</label>
            <?php if (!empty($kyc['pan_image'])): ?>
            <div class="mb-1">
                <a href="<?= imgUrl($kyc['pan_image']) ?>" target="_blank">
                    <img src="<?= imgUrl($kyc['pan_image']) ?>" class="img-fluid rounded" style="max-height:80px;object-fit:cover;">
                </a>
            </div>
            <?php endif; ?>
            <input type="file" name="pan_image" class="form-control" accept="image/*"
                   onchange="previewImg(this,'prev_pan')">
            <img id="prev_pan" src="" class="img-fluid rounded mt-1 d-none" style="max-height:70px;">
        </div>
    </div>

    <button type="submit" class="btn btn-erp w-100 py-3" style="font-size:1rem;">
        <i class="bi bi-cloud-upload-fill me-2"></i>
        <?= $kyc ? 'Update KYC Details' : 'Submit KYC Details' ?>
    </button>
    <?php if ($kyc && !empty($kyc['updated_at'])): ?>
    <p class="text-center text-muted mt-2" style="font-size:.78rem;">
        Last updated: <?= formatDt($kyc['updated_at']) ?>
    </p>
    <?php endif; ?>
</form>

<?php
$extraJs = <<<JS
<script>
function previewImg(input, previewId) {
    const prev = document.getElementById(previewId);
    if (!prev || !input.files[0]) return;
    const reader = new FileReader();
    reader.onload = function(e) {
        prev.src = e.target.result;
        prev.classList.remove('d-none');
    };
    reader.readAsDataURL(input.files[0]);
}
// Auto uppercase IFSC and PAN
document.querySelector('[name=bank_ifsc]')?.addEventListener('input', function() { this.value = this.value.toUpperCase(); });
document.querySelector('[name=pan_number]')?.addEventListener('input', function() { this.value = this.value.toUpperCase(); });
</script>
JS;
include __DIR__ . '/../../includes/footer.php';
?>
