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

$db = getDBConnection();

// 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) {}

// ── Single MR detail view ─────────────────────────────────────
$viewId = (int)($_GET['id'] ?? 0);
if ($viewId) {
    $mr = dbRow($db,
        "SELECT u.id, u.full_name AS u_name, u.username, u.phone AS u_phone, u.division, u.role,
                k.*
         FROM users u
         LEFT JOIN mr_kyc k ON k.user_id = u.id
         WHERE u.id = ? AND u.role = 'mr'", [$viewId]);
    if (!$mr) redirect(BASE_URL . '/modules/admin/mr_list.php');

    $pageTitle = 'MR Details — ' . h($mr['u_name']);
    include __DIR__ . '/../../includes/header.php';

    $field = function($label, $val, $icon = 'dash') use ($mr) {
        $v = h(trim($val ?? ''));
        $empty = $v === '' ? 'text-muted' : '';
        $display = $v !== '' ? $v : '—';
        echo "<div class='detail-row'><span class='detail-label'><i class='bi bi-{$icon} me-1'></i>{$label}</span><span class='{$empty}'>{$display}</span></div>";
    };
    $imgField = function($label, $path) {
        echo "<div class='detail-row align-items-start'><span class='detail-label'>{$label}</span>";
        if ($path) {
            echo "<a href='" . imgUrl($path) . "' target='_blank'>
                    <img src='" . imgUrl($path) . "' style='max-width:130px;max-height:90px;object-fit:cover;border-radius:8px;border:1px solid #e2e8f0;'>
                  </a>";
        } else {
            echo "<span class='text-muted'>—</span>";
        }
        echo "</div>";
    };
    ?>

    <div class="page-header">
        <div>
            <h1><i class="bi bi-person-vcard-fill me-2 text-primary"></i><?= h($mr['u_name']) ?></h1>
            <nav aria-label="breadcrumb"><ol class="breadcrumb mb-0" style="font-size:.8rem;">
                <li class="breadcrumb-item"><a href="<?= BASE_URL ?>/modules/admin/mr_list.php">MR KYC List</a></li>
                <li class="breadcrumb-item active">Details</li>
            </ol></nav>
        </div>
        <div class="d-flex gap-2">
            <a href="<?= BASE_URL ?>/modules/admin/mr_export.php?id=<?= $viewId ?>"
               class="btn btn-success btn-sm">
                <i class="bi bi-file-earmark-excel me-1"></i>Export Excel
            </a>
            <a href="<?= BASE_URL ?>/modules/admin/mr_list.php" class="btn btn-outline-secondary btn-sm">
                <i class="bi bi-arrow-left me-1"></i>Back
            </a>
        </div>
    </div>

    <style>
    .detail-row { display:flex; gap:12px; padding:10px 0; border-bottom:1px solid var(--erp-border,#e2e8f0); align-items:center; font-size:.88rem; }
    .detail-row:last-child { border-bottom:none; }
    .detail-label { min-width:160px; font-weight:600; color:#6b7280; font-size:.8rem; flex-shrink:0; }
    </style>

    <!-- Basic -->
    <div class="erp-card mb-3">
        <h6 class="fw-bold mb-3"><i class="bi bi-person-fill text-primary me-2"></i>Basic Details</h6>
        <?php
        $field('Full Name',      $mr['full_name']       ?: $mr['u_name'], 'person');
        $field('Mobile (KYC)',   $mr['mobile'],           'phone');
        $field('Mobile (Login)', $mr['u_phone'],          'telephone');
        $field('Username',       $mr['username'],         'at');
        $field('Division',       $mr['division'],         'geo');
        $field('Current Address',$mr['current_address'],  'house');
        ?>
    </div>

    <!-- Aadhaar -->
    <div class="erp-card mb-3">
        <h6 class="fw-bold mb-3"><i class="bi bi-card-heading text-info me-2"></i>Aadhaar Details</h6>
        <?php
        $field('Aadhaar Number', $mr['aadhaar_number'], 'upc');
        $field('Aadhaar Address',$mr['aadhaar_address'],'house-door');
        $imgField('Front Photo', $mr['aadhaar_front']);
        $imgField('Back Photo',  $mr['aadhaar_back']);
        ?>
    </div>

    <!-- Bank -->
    <div class="erp-card mb-3">
        <h6 class="fw-bold mb-3"><i class="bi bi-bank text-success me-2"></i>Bank Details</h6>
        <?php
        $field('Account Number', $mr['bank_account'],   'wallet2');
        $field('IFSC Code',      $mr['bank_ifsc'],      'building');
        $imgField('Passbook',    $mr['passbook_image']);
        ?>
    </div>

    <!-- Employment -->
    <div class="erp-card mb-3">
        <h6 class="fw-bold mb-3"><i class="bi bi-briefcase-fill text-warning me-2"></i>Employment Details</h6>
        <?php
        $field('PF Number',  $mr['pf_number'],  'shield-check');
        $field('ESI Number', $mr['esi_number'], 'heart-pulse');
        ?>
    </div>

    <!-- PAN -->
    <div class="erp-card mb-3">
        <h6 class="fw-bold mb-3"><i class="bi bi-credit-card-2-front-fill text-danger me-2"></i>PAN Details</h6>
        <?php
        $field('PAN Number', $mr['pan_number'], 'credit-card');
        $imgField('PAN Card Photo', $mr['pan_image']);
        ?>
    </div>

    <?php if (!empty($mr['submitted_at'])): ?>
    <p class="text-muted text-center" style="font-size:.78rem;">
        Submitted: <?= formatDt($mr['submitted_at']) ?> &nbsp;|&nbsp; Updated: <?= formatDt($mr['updated_at']) ?>
    </p>
    <?php endif; ?>

    <?php
    include __DIR__ . '/../../includes/footer.php';
    exit;
}

// ── List View ─────────────────────────────────────────────────
$filter = $_GET['filter'] ?? 'all'; // all | submitted | pending
$search = trim($_GET['q'] ?? '');

$sql = "SELECT u.id, u.full_name, u.phone, u.division, u.username,
               k.id AS kyc_id, k.mobile, k.aadhaar_number, k.bank_account,
               k.pan_number, k.submitted_at, k.updated_at
        FROM users u
        LEFT JOIN mr_kyc k ON k.user_id = u.id
        WHERE u.role = 'mr' AND u.is_active = 1";
$params = array();
if ($filter === 'submitted') { $sql .= " AND k.id IS NOT NULL"; }
if ($filter === 'pending')   { $sql .= " AND k.id IS NULL"; }
if ($search) { $sql .= " AND u.full_name LIKE ?"; $params[] = "%$search%"; }
$sql .= " ORDER BY u.full_name";

$mrs      = dbRows($db, $sql, $params);
$total    = count($mrs);
$submitted = count(array_filter($mrs, function($r){ return !empty($r['kyc_id']); }));
$pending   = $total - $submitted;

$pageTitle = 'MR KYC List';
include __DIR__ . '/../../includes/header.php';
?>

<div class="page-header">
    <div>
        <h1><i class="bi bi-people-fill me-2 text-primary"></i>MR KYC List</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">MR KYC List</li>
        </ol></nav>
    </div>
    <a href="<?= BASE_URL ?>/modules/admin/mr_export.php" class="btn btn-success">
        <i class="bi bi-file-earmark-excel me-1"></i>Export Excel
    </a>
</div>

<!-- Stats -->
<div class="stats-grid mb-3" style="grid-template-columns:repeat(3,1fr);">
    <div class="stat-card">
        <div class="stat-card-icon blue"><i class="bi bi-people-fill"></i></div>
        <div><h3>Total MRs</h3><p><?= $total ?></p></div>
    </div>
    <div class="stat-card">
        <div class="stat-card-icon green"><i class="bi bi-check-circle-fill"></i></div>
        <div><h3>Submitted</h3><p><?= $submitted ?></p></div>
    </div>
    <div class="stat-card">
        <div class="stat-card-icon orange"><i class="bi bi-clock-fill"></i></div>
        <div><h3>Pending</h3><p><?= $pending ?></p></div>
    </div>
</div>

<!-- Filter + Search -->
<div class="erp-card mb-3">
    <form method="GET" class="row g-2 align-items-end">
        <div class="col">
            <input type="text" name="q" class="form-control" placeholder="Search by name…"
                   value="<?= h($search) ?>">
        </div>
        <div class="col-auto">
            <select name="filter" class="form-select">
                <option value="all"       <?= $filter==='all'       ? 'selected':'' ?>>All</option>
                <option value="submitted" <?= $filter==='submitted' ? 'selected':'' ?>>Submitted</option>
                <option value="pending"   <?= $filter==='pending'   ? 'selected':'' ?>>Pending</option>
            </select>
        </div>
        <div class="col-auto d-flex gap-2">
            <button type="submit" class="btn btn-erp"><i class="bi bi-funnel me-1"></i>Filter</button>
            <a href="?" class="btn btn-outline-secondary"><i class="bi bi-x"></i></a>
        </div>
    </form>
</div>

<!-- Table -->
<div class="erp-card">
    <?php if (empty($mrs)): ?>
    <div class="text-center py-5 text-muted">
        <i class="bi bi-people" style="font-size:2.5rem;opacity:.3;"></i>
        <p class="mt-2">No meter readers found.</p>
    </div>
    <?php else: ?>
    <div class="table-responsive">
        <table class="table table-hover mb-0" style="font-size:.84rem;">
            <thead class="table-light">
                <tr>
                    <th>#</th>
                    <th>Meter Reader</th>
                    <th>Mobile</th>
                    <th>Division</th>
                    <th class="text-center">Aadhaar</th>
                    <th class="text-center">Bank</th>
                    <th class="text-center">PAN</th>
                    <th class="text-center">KYC Status</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($mrs as $i => $m): ?>
                <?php $done = !empty($m['kyc_id']); ?>
                <tr>
                    <td class="text-muted"><?= $i + 1 ?></td>
                    <td>
                        <div class="fw-semibold"><?= h($m['full_name']) ?></div>
                        <small class="text-muted"><?= h($m['username']) ?></small>
                    </td>
                    <td><?= h($m['mobile'] ?: $m['phone'] ?: '—') ?></td>
                    <td><?= h($m['division'] ?? '—') ?></td>
                    <td class="text-center">
                        <?php if ($done && $m['aadhaar_number']): ?>
                        <i class="bi bi-check-circle-fill text-success"></i>
                        <?php else: ?><i class="bi bi-x-circle text-danger"></i><?php endif; ?>
                    </td>
                    <td class="text-center">
                        <?php if ($done && $m['bank_account']): ?>
                        <i class="bi bi-check-circle-fill text-success"></i>
                        <?php else: ?><i class="bi bi-x-circle text-danger"></i><?php endif; ?>
                    </td>
                    <td class="text-center">
                        <?php if ($done && $m['pan_number']): ?>
                        <i class="bi bi-check-circle-fill text-success"></i>
                        <?php else: ?><i class="bi bi-x-circle text-danger"></i><?php endif; ?>
                    </td>
                    <td class="text-center">
                        <?php if ($done): ?>
                        <span class="badge bg-success">Submitted</span>
                        <?php else: ?>
                        <span class="badge bg-warning text-dark">Pending</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if ($done): ?>
                        <a href="?id=<?= $m['id'] ?>" class="btn btn-sm btn-outline-primary">
                            <i class="bi bi-eye me-1"></i>View
                        </a>
                        <?php else: ?>
                        <span class="text-muted" style="font-size:.78rem;">Not submitted</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

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