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

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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!validateCsrfToken($_POST['csrf_token'] ?? '')) {
        $error = 'Invalid request. Please try again.';
    } else {
        $billType       = $_POST['bill_type'] ?? '';
        $deliveryRemark = $_POST['delivery_remark'] ?? '';
        $otherRemark    = trim($_POST['other_remark'] ?? '');
        $imageData      = $_POST['image_data'] ?? '';
        $gpsLat         = trim($_POST['gps_lat'] ?? '');
        $gpsLng         = trim($_POST['gps_lng'] ?? '');
        $consumerId     = (int)($_POST['consumer_id'] ?? 0);
        $consumerName   = trim($_POST['consumer_name_manual'] ?? '');
        $meterNumber    = trim($_POST['meter_number_manual'] ?? '');

        $validBillTypes   = ['smart_meter','normal_meter'];
        $validRemarks     = ['meter_par_rakha','consumer_ko_diya'];

        if (!$consumerId) {
            $error = 'Please search and select a consumer first.';
        } elseif (!in_array($billType, $validBillTypes)) {
            $error = 'Please select bill type.';
        } elseif (!in_array($deliveryRemark, $validRemarks)) {
            $error = 'Please select delivery remark.';
        } elseif (empty($imageData)) {
            $error = 'Please capture an image before submitting.';
        } elseif ($consumerId && ($dupBill = dbRow($db,
            "SELECT b.created_at, u.full_name AS mr_name
             FROM bills b LEFT JOIN users u ON u.id=b.user_id
             WHERE b.consumer_id=? AND YEAR(b.created_at)=YEAR(CURDATE()) AND MONTH(b.created_at)=MONTH(CURDATE())
             ORDER BY b.created_at DESC LIMIT 1",
            [$consumerId]))) {
            $cName = dbRow($db, "SELECT consumer_name FROM consumers WHERE id=?", [$consumerId]);
            $error = 'Bill already distributed for <strong>' . h($cName['consumer_name'] ?? 'this consumer') . '</strong>'
                   . ' by <strong>' . h($dupBill['mr_name'] ?? 'Meter Reader') . '</strong>'
                   . ' on <strong>' . date('d M Y', strtotime($dupBill['created_at'])) . '</strong>'
                   . ' (' . date('F Y') . '). Billing will resume from next month';
        } else {
            $imgPath = saveBase64Image($imageData, 'bills');
            if (!$imgPath) {
                $error = 'Image save failed. Please try again.';
            } else {
                // If consumer was searched, get name/meter from DB
                if ($consumerId) {
                    $c = dbRow($db, "SELECT consumer_name,meter_number FROM consumers WHERE id=?", [$consumerId]);
                    if ($c) { $consumerName = $c['consumer_name']; $meterNumber = $c['meter_number']; }
                }
                try {
                    $db->prepare(
                        "INSERT INTO bills
                         (user_id,consumer_id,consumer_name,meter_number,bill_type,delivery_remark,other_remark,image_path,gps_lat,gps_lng)
                         VALUES (?,?,?,?,?,?,?,?,?,?)"
                    )->execute([
                        $uid,
                        $consumerId ?: null,
                        $consumerName ?: null,
                        $meterNumber ?: null,
                        $billType, $deliveryRemark,
                        $otherRemark ?: null,
                        $imgPath,
                        $gpsLat ?: null, $gpsLng ?: null
                    ]);
                    $success = 'Bill distribution recorded successfully!';
                } catch (PDOException $e) {
                    @unlink(UPLOAD_PATH . $imgPath);
                    $error = 'Database error. Please try again.';
                }
            }
        }
    }
}

$pageTitle = 'Bill Distribution';
$extraHead = '<meta name="mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-capable" content="yes">';
include __DIR__ . '/../../includes/header.php';
?>

<div class="page-header">
    <div>
        <h1><i class="bi bi-receipt-cutoff me-2 text-success"></i>Bill Distribution</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">Bill Distribution</li>
        </ol></nav>
    </div>
</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) ?>
    <a href="<?= BASE_URL ?>/modules/bills/add.php" class="ms-auto btn btn-sm btn-success">New Entry</a>
</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 flex-shrink-0"></i><span><?= $error ?></span>
</div>
<?php endif; ?>

<form method="POST" id="billForm" novalidate>
    <input type="hidden" name="csrf_token" value="<?= generateCsrfToken() ?>">
    <input type="hidden" name="image_data" id="image_data" value="">
    <input type="hidden" name="gps_lat" id="gps_lat" value="">
    <input type="hidden" name="gps_lng" id="gps_lng" value="">
    <input type="hidden" name="gps_address" id="gps_address" value="">
    <input type="hidden" name="consumer_id" id="consumer_id" value="">
    <input type="hidden" id="mr_name_val" value="<?= h($mrN) ?>">

    <!-- ── Consumer Search (Required) ───────────────────── -->
    <div class="erp-card mb-3">
        <h6 class="fw-bold mb-3">
            <span class="step-badge">1</span>Consumer <span class="text-danger">*</span>
            <small class="text-muted fw-normal ms-1" style="font-size:.75rem;">Meter / Connection number se search karo</small>
        </h6>
        <div class="row g-2 align-items-end">
            <div class="col">
                <input type="text" id="searchQuery" class="form-control"
                       placeholder="Meter number ya connection number" autocomplete="off">
            </div>
            <div class="col-auto">
                <button type="button" class="btn btn-erp" onclick="searchConsumer('kcc', true)">
                    <i class="bi bi-search me-1"></i>Search
                </button>
            </div>
        </div>
        <div id="consumerResult" class="mt-2"></div>
    </div>

    <!-- Camera + Details hidden until consumer selected -->
    <div id="formSection" class="d-none">

    <!-- ── Camera ─────────────────────────────────────────── -->
    <div class="erp-card mb-3">
        <h6 class="fw-bold mb-3">
            <span class="step-badge">2</span>Capture Photo
        </h6>
        <div class="d-flex align-items-center gap-2 mb-3">
            <button type="button" class="btn btn-sm btn-outline-secondary" id="gpsBtn" onclick="getGPS()">
                <i class="bi bi-geo-alt-fill me-1"></i>Get GPS
            </button>
            <span id="gpsDisplay" class="text-muted" style="font-size:.78rem;">GPS not captured</span>
        </div>

        <div id="videoWrapper">
            <div class="camera-container">
                <video id="cameraFeed" autoplay playsinline muted class="camera-video"></video>
                <div class="camera-overlay">
                    <span id="camOverlayText" style="font-size:.72rem;"></span>
                </div>
            </div>
            <div class="d-flex gap-2 mt-2">
                <button type="button" class="btn btn-erp flex-fill" onclick="captureImage()">
                    <i class="bi bi-camera-fill me-2"></i>Capture
                </button>
                <button type="button" class="btn btn-outline-secondary" onclick="switchCamera()">
                    <i class="bi bi-arrow-repeat"></i>
                </button>
            </div>
            <button type="button" class="btn btn-outline-primary w-100 mt-2" onclick="startCamera()">
                <i class="bi bi-camera me-2"></i>Start Camera
            </button>
        </div>

        <div id="previewWrapper" class="d-none">
            <img id="imagePreview" src="" alt="Captured" class="capture-preview">
            <div class="d-flex gap-2 mt-2">
                <button type="button" class="btn btn-outline-secondary flex-fill" onclick="retakePhoto()">
                    <i class="bi bi-arrow-counterclockwise me-2"></i>Retake
                </button>
                <div class="text-success d-flex align-items-center gap-1 flex-fill justify-content-center">
                    <i class="bi bi-check-circle-fill"></i><span style="font-size:.85rem;">Photo ready</span>
                </div>
            </div>
        </div>

        <canvas id="captureCanvas" class="d-none"></canvas>
    </div>

    <!-- ── Bill Details ────────────────────────────────────── -->
    <div class="erp-card mb-3">
        <h6 class="fw-bold mb-3"><span class="step-badge">3</span>Bill Details</h6>

        <div class="mb-3">
            <label class="form-label fw-semibold" style="font-size:.88rem;">Bill Type <span class="text-danger">*</span></label>
            <div class="d-flex flex-column gap-2">
                <label class="status-option <?= ($_POST['bill_type']??'')==='smart_meter'?'selected':'' ?>">
                    <input type="radio" name="bill_type" value="smart_meter" class="d-none"
                           <?= ($_POST['bill_type']??'')==='smart_meter'?'checked':'' ?>>
                    <i class="bi bi-wifi text-info"></i>
                    <div>
                        <div class="fw-semibold">Smart Meter Bill</div>
                        <small class="text-muted">Smart meter bill delivered</small>
                    </div>
                </label>
                <label class="status-option <?= ($_POST['bill_type']??'')==='normal_meter'?'selected':'' ?>">
                    <input type="radio" name="bill_type" value="normal_meter" class="d-none"
                           <?= ($_POST['bill_type']??'')==='normal_meter'?'checked':'' ?>>
                    <i class="bi bi-file-earmark-text text-warning"></i>
                    <div>
                        <div class="fw-semibold">Normal Meter Bill</div>
                        <small class="text-muted">Normal meter bill delivered</small>
                    </div>
                </label>
            </div>
        </div>

        <div class="mb-3">
            <label class="form-label fw-semibold" style="font-size:.88rem;">Delivery Remark <span class="text-danger">*</span></label>
            <div class="d-flex flex-column gap-2">
                <label class="status-option <?= ($_POST['delivery_remark']??'')==='meter_par_rakha'?'selected':'' ?>">
                    <input type="radio" name="delivery_remark" value="meter_par_rakha" class="d-none"
                           <?= ($_POST['delivery_remark']??'')==='meter_par_rakha'?'checked':'' ?>>
                    <i class="bi bi-box-seam text-secondary"></i>
                    <div>
                        <div class="fw-semibold">Meter par rakh diya tha</div>
                        <small class="text-muted">Bill placed on the meter</small>
                    </div>
                </label>
                <label class="status-option <?= ($_POST['delivery_remark']??'')==='consumer_ko_diya'?'selected':'' ?>">
                    <input type="radio" name="delivery_remark" value="consumer_ko_diya" class="d-none"
                           <?= ($_POST['delivery_remark']??'')==='consumer_ko_diya'?'checked':'' ?>>
                    <i class="bi bi-person-check text-success"></i>
                    <div>
                        <div class="fw-semibold">Consumer ko diya tha</div>
                        <small class="text-muted">Bill handed to consumer</small>
                    </div>
                </label>
            </div>
        </div>

        <div class="mb-2">
            <label class="form-label fw-semibold" style="font-size:.88rem;">Additional Remark</label>
            <textarea name="other_remark" class="form-control" rows="2"
                      placeholder="Any other notes..."><?= h($_POST['other_remark'] ?? '') ?></textarea>
        </div>
    </div>

    <button type="submit" class="btn btn-erp w-100 py-3" id="submitBtn" style="font-size:1rem;background:var(--erp-success);">
        <i class="bi bi-cloud-upload-fill me-2"></i>Submit Bill Record
    </button>
    <div class="text-center mt-2">
        <a href="<?= BASE_URL ?>/modules/dashboard/index.php" class="text-muted" style="font-size:.82rem;">Cancel</a>
    </div>

    </div><!-- /#formSection -->
</form>

<?php
$extraJs = <<<JS
<script>
window.EMRS_CHECK_BILL = true;
document.querySelectorAll('.status-option').forEach(opt => {
    opt.addEventListener('click', () => {
        const grp = opt.closest('.d-flex');
        grp?.querySelectorAll('.status-option').forEach(o => o.classList.remove('selected'));
        opt.classList.add('selected');
        opt.querySelector('input[type=radio]').checked = true;
    });
});
document.getElementById('billForm')?.addEventListener('submit', function(e) {
    const cid    = document.getElementById('consumer_id').value;
    const imgData = document.getElementById('image_data').value;
    if (!cid)     { e.preventDefault(); showAlert('Please search and select a consumer first.', 'danger'); return; }
    if (!imgData) { e.preventDefault(); showAlert('Please capture an image first.', 'danger'); return; }
    document.getElementById('submitBtn').disabled = true;
    document.getElementById('submitBtn').innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Saving...';
});
// Start camera only after consumer is selected
document.addEventListener('cameraReady', startCamera);
setInterval(() => { const el = document.getElementById('camOverlayText'); if (el) el.textContent = new Date().toLocaleString('en-IN'); }, 1000);
</script>
JS;
include __DIR__ . '/../../includes/footer.php';
?>
