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

$type = in_array($_GET['type'] ?? '', ['solar','kcc']) ? $_GET['type'] : 'solar';
$typeLabel = strtoupper($type);

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

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

// ── Handle form submission ────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!validateCsrfToken($_POST['csrf_token'] ?? '')) {
        $error = 'Invalid request. Please try again.';
    } else {
        $consumerId  = (int)($_POST['consumer_id'] ?? 0);
        $status      = $_POST['status'] ?? '';
        $imageData   = $_POST['image_data'] ?? '';
        $gpsLat      = trim($_POST['gps_lat'] ?? '');
        $gpsLng      = trim($_POST['gps_lng'] ?? '');
        $remark      = trim($_POST['remark'] ?? '');
        $readingDate = date('Y-m-d');

        $validStatuses = ['mri_done','smart_meter','meter_port_defective'];

        if (!$consumerId) {
            $error = 'Please search and select a consumer first.';
        } elseif (!in_array($status, $validStatuses)) {
            $error = 'Please select a valid status.';
        } elseif (empty($imageData)) {
            $error = 'Please capture an image before submitting.';
        } else {
            // Save image
            $imgPath = saveBase64Image($imageData, 'readings');
            if (!$imgPath) {
                $error = 'Image save failed. Please try again.';
            } else {
                try {
                    $db->prepare(
                        "INSERT INTO readings
                         (consumer_id,user_id,reading_type,status,image_path,gps_lat,gps_lng,mr_name,remark,reading_date)
                         VALUES (?,?,?,?,?,?,?,?,?,?)"
                    )->execute([
                        $consumerId, $uid, $type, $status,
                        $imgPath, $gpsLat ?: null, $gpsLng ?: null,
                        $mrN, $remark ?: null, $readingDate
                    ]);
                    $success = "{$typeLabel} reading saved successfully!";
                } catch (PDOException $e) {
                    @unlink(UPLOAD_PATH . $imgPath);
                    $error = 'Database error. Please try again.';
                }
            }
        }
    }
}

$pageTitle = "{$typeLabel} Reading";
$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>
            <?php if ($type === 'solar'): ?>
            <i class="bi bi-sun-fill me-2 text-warning"></i>
            <?php else: ?>
            <i class="bi bi-lightning-fill me-2 text-info"></i>
            <?php endif; ?>
            <?= $typeLabel ?> Meter Reading
        </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"><?= $typeLabel ?> Reading</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/readings/add.php?type=<?= $type ?>" class="ms-auto btn btn-sm btn-success">New Reading</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"></i><?= h($error) ?>
</div>
<?php endif; ?>

<!-- ── STEP 1: Consumer Search ─────────────────────────────── -->
<div class="erp-card mb-3" id="searchSection">
    <h6 class="fw-bold mb-3">
        <span class="step-badge">1</span>Search Consumer
    </h6>
    <div class="row g-2 align-items-end">
        <div class="col">
            <label class="form-label" style="font-size:.82rem;">Meter Number / Connection Number</label>
            <input type="text" id="searchQuery" class="form-control"
                   placeholder="Enter meter or connection number" autocomplete="off">
        </div>
        <div class="col-auto">
            <button type="button" class="btn btn-erp" onclick="searchConsumer('<?= $type ?>')">
                <i class="bi bi-search me-1"></i>Search
            </button>
        </div>
    </div>
    <div id="consumerResult" class="mt-2"></div>
</div>

<!-- ── STEP 2: Camera + Reading Form ──────────────────────── -->
<div id="formSection" class="d-none">
    <form method="POST" id="readingForm" novalidate>
        <input type="hidden" name="csrf_token" value="<?= generateCsrfToken() ?>">
        <input type="hidden" name="consumer_id" id="consumer_id" value="">
        <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="">
        <!-- MR name for watermark -->
        <input type="hidden" id="mr_name_val" value="<?= h($mrN) ?>">

        <!-- ── Camera Section ─────────────────────────────── -->
        <div class="erp-card mb-3">
            <h6 class="fw-bold mb-3">
                <span class="step-badge">2</span>Capture Image
                <small class="text-muted fw-normal ms-2" style="font-size:.75rem;">GPS &amp; timestamp auto-added</small>
            </h6>

            <!-- GPS status -->
            <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 yet</span>
            </div>

            <!-- Video preview -->
            <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" id="captureBtn" onclick="captureImage()">
                        <i class="bi bi-camera-fill me-2"></i>Capture Photo
                    </button>
                    <button type="button" class="btn btn-outline-secondary" id="switchCamBtn" onclick="switchCamera()" title="Switch camera">
                        <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>

            <!-- Image preview (after capture) -->
            <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 captured</span>
                    </div>
                </div>
            </div>

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

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

            <div class="mb-3">
                <label class="form-label fw-semibold" style="font-size:.88rem;">Status <span class="text-danger">*</span></label>
                <div class="d-flex flex-column gap-2">
                    <label class="status-option <?= ($_POST['status']??'')==='mri_done'?'selected':'' ?>">
                        <input type="radio" name="status" value="mri_done" class="d-none" <?= ($_POST['status']??'')==='mri_done'?'checked':'' ?>>
                        <i class="bi bi-check-circle-fill text-success"></i>
                        <div>
                            <div class="fw-semibold">MRI Done</div>
                            <small class="text-muted">Meter reading successfully captured</small>
                        </div>
                    </label>
                    <label class="status-option <?= ($_POST['status']??'')==='smart_meter'?'selected':'' ?>">
                        <input type="radio" name="status" value="smart_meter" class="d-none" <?= ($_POST['status']??'')==='smart_meter'?'checked':'' ?>>
                        <i class="bi bi-wifi text-info"></i>
                        <div>
                            <div class="fw-semibold">Smart Meter</div>
                            <small class="text-muted">Smart meter installed / replaced</small>
                        </div>
                    </label>
                    <label class="status-option <?= ($_POST['status']??'')==='meter_port_defective'?'selected':'' ?>">
                        <input type="radio" name="status" value="meter_port_defective" class="d-none" <?= ($_POST['status']??'')==='meter_port_defective'?'checked':'' ?>>
                        <i class="bi bi-exclamation-triangle-fill text-danger"></i>
                        <div>
                            <div class="fw-semibold">Meter Port Defective</div>
                            <small class="text-muted">Meter or port has a defect</small>
                        </div>
                    </label>
                </div>
            </div>

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

        <!-- ── Submit ─────────────────────────────────────── -->
        <button type="submit" class="btn btn-erp w-100 py-3" id="submitBtn" style="font-size:1rem;">
            <i class="bi bi-cloud-upload-fill me-2"></i>Submit <?= $typeLabel ?> Reading
        </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>
    </form>
</div>

<?php
$extraJs = <<<JS
<script>
// Activate status option visual
document.querySelectorAll('.status-option').forEach(opt => {
    const radio = opt.querySelector('input[type=radio]');
    opt.addEventListener('click', () => {
        document.querySelectorAll('.status-option').forEach(o => o.classList.remove('selected'));
        opt.classList.add('selected');
        radio.checked = true;
    });
});

// Form validation before submit
document.getElementById('readingForm')?.addEventListener('submit', function(e) {
    const imgData = document.getElementById('image_data').value;
    const status  = document.querySelector('input[name="status"]:checked');
    if (!imgData) { e.preventDefault(); showAlert('Please capture an image first.', 'danger'); return; }
    if (!status)  { e.preventDefault(); showAlert('Please select a reading status.', 'danger'); return; }
    document.getElementById('submitBtn').disabled = true;
    document.getElementById('submitBtn').innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Saving...';
});

// Auto-start camera when form section is shown
document.addEventListener('cameraReady', startCamera);

// Live overlay text update
setInterval(() => {
    const el = document.getElementById('camOverlayText');
    if (el) el.textContent = new Date().toLocaleString('en-IN');
}, 1000);
</script>
JS;
include __DIR__ . '/../../includes/footer.php';
?>
