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

$db     = getDBConnection();
$id     = (int)($_GET['id'] ?? 0);
$isEdit = ($id > 0);
$cons   = [];

if ($isEdit) {
    $cons = dbRow($db, "SELECT * FROM consumers WHERE id=?", [$id]);
    if (!$cons) redirect(BASE_URL . '/modules/admin/consumers.php');
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!validateCsrfToken($_POST['csrf_token'] ?? '')) {
        $error = 'Invalid request.';
    } else {
        $name    = trim($_POST['consumer_name'] ?? '');
        $meter   = trim($_POST['meter_number'] ?? '');
        $conn    = trim($_POST['connection_number'] ?? '');
        $address = trim($_POST['address'] ?? '');
        $division= trim($_POST['division'] ?? '');
        $type    = $_POST['type'] ?? 'kcc';
        $active  = isset($_POST['is_active']) ? 1 : 0;

        if (!$name || !$meter || !$conn) {
            $error = 'Consumer name, meter number, and connection number are required.';
        } elseif (!in_array($type, ['solar','kcc','both'])) {
            $error = 'Invalid type.';
        } else {
            try {
                if ($isEdit) {
                    $db->prepare("UPDATE consumers SET consumer_name=?,meter_number=?,connection_number=?,address=?,division=?,type=?,is_active=? WHERE id=?")
                       ->execute([$name,$meter,$conn,$address?:null,$division?:null,$type,$active,$id]);
                    $success = 'Consumer updated.';
                    $cons    = dbRow($db, "SELECT * FROM consumers WHERE id=?", [$id]);
                } else {
                    $db->prepare("INSERT INTO consumers (consumer_name,meter_number,connection_number,address,division,type,is_active) VALUES (?,?,?,?,?,?,?)")
                       ->execute([$name,$meter,$conn,$address?:null,$division?:null,$type,$active]);
                    redirect(BASE_URL . '/modules/admin/consumers.php');
                }
            } catch (PDOException $e) {
                $error = str_contains($e->getMessage(),'Duplicate')
                    ? 'Meter number or connection number already exists.'
                    : 'Database error: ' . $e->getMessage();
            }
        }
    }
}

$pageTitle = $isEdit ? 'Edit Consumer' : 'Add Consumer';
include __DIR__ . '/../../includes/header.php';
?>

<div class="page-header">
    <div>
        <h1><i class="bi bi-person-badge-fill me-2"></i><?= $pageTitle ?></h1>
        <nav aria-label="breadcrumb"><ol class="breadcrumb mb-0" style="font-size:.8rem;">
            <li class="breadcrumb-item"><a href="<?= BASE_URL ?>/modules/admin/consumers.php">Consumers</a></li>
            <li class="breadcrumb-item active"><?= $pageTitle ?></li>
        </ol></nav>
    </div>
</div>

<?php if ($error):   ?><div class="alert alert-danger"><?= h($error) ?></div><?php endif; ?>
<?php if ($success): ?><div class="alert alert-success"><?= h($success) ?></div><?php endif; ?>

<div class="erp-card" style="max-width:560px;">
    <form method="POST" novalidate>
        <input type="hidden" name="csrf_token" value="<?= generateCsrfToken() ?>">

        <div class="mb-3">
            <label class="form-label fw-semibold">Consumer Name <span class="text-danger">*</span></label>
            <input type="text" name="consumer_name" class="form-control" required
                   value="<?= h($cons['consumer_name'] ?? '') ?>" placeholder="Full consumer name">
        </div>

        <div class="row g-3 mb-3">
            <div class="col-6">
                <label class="form-label fw-semibold">Meter Number <span class="text-danger">*</span></label>
                <input type="text" name="meter_number" class="form-control" required
                       value="<?= h($cons['meter_number'] ?? '') ?>" placeholder="e.g. MTR001">
            </div>
            <div class="col-6">
                <label class="form-label fw-semibold">Connection Number <span class="text-danger">*</span></label>
                <input type="text" name="connection_number" class="form-control" required
                       value="<?= h($cons['connection_number'] ?? '') ?>" placeholder="e.g. CON001">
            </div>
        </div>

        <div class="mb-3">
            <label class="form-label fw-semibold">Consumer Type <span class="text-danger">*</span></label>
            <div class="d-flex gap-3">
                <?php foreach (['solar'=>'Solar','kcc'=>'KCC','both'=>'Both (Solar+KCC)'] as $v=>$l): ?>
                <label class="d-flex align-items-center gap-1" style="cursor:pointer;">
                    <input type="radio" name="type" value="<?= $v ?>"
                           <?= ($cons['type']??'kcc')===$v?'checked':'' ?>>
                    <?= $l ?>
                </label>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="mb-3">
            <label class="form-label fw-semibold">Address</label>
            <textarea name="address" class="form-control" rows="2"><?= h($cons['address'] ?? '') ?></textarea>
        </div>

        <div class="mb-3">
            <label class="form-label fw-semibold">Division / Sub-division</label>
            <?php
            $allAreas = [
                'ROORKEE_SD-I',
                'ROORKEE_SD-II',
                'EDSD DHANORI',
                'EDSD-I RAMNAGAR ROORKEE',
                'EDSD-II RAMNAGAR ROORKEE',
                'EDSD HIMALAYAN',
                'MANGLORE',
                'EDSD JHEBREDA',
                'LANDHAURA',
            ];
            $groupLabels = [
                'ROORKEE_SD-I'             => 'Roorkee Urban',
                'ROORKEE_SD-II'            => 'Roorkee Urban',
                'EDSD DHANORI'             => 'Roorkee Urban',
                'EDSD-I RAMNAGAR ROORKEE'  => 'Ramnagar',
                'EDSD-II RAMNAGAR ROORKEE' => 'Ramnagar',
                'EDSD HIMALAYAN'           => 'Ramnagar',
                'MANGLORE'                 => 'Roorkee Rural',
                'EDSD JHEBREDA'            => 'Roorkee Rural',
                'LANDHAURA'                => 'Roorkee Rural',
            ];
            $groups = [];
            foreach ($allAreas as $a) {
                $g = $groupLabels[$a] ?? $a;
                $groups[$g][] = $a;
            }
            ?>
            <select name="division" class="form-select">
                <option value="">-- Select Sub-division --</option>
                <?php foreach ($groups as $grp => $items): ?>
                <optgroup label="<?= h($grp) ?>">
                    <?php foreach ($items as $area): ?>
                    <option value="<?= h($area) ?>" <?= ($cons['division']??'')===$area?'selected':'' ?>><?= h($area) ?></option>
                    <?php endforeach; ?>
                </optgroup>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="mb-4">
            <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" name="is_active" id="isActive"
                       <?= ($cons['is_active'] ?? 1) ? 'checked' : '' ?>>
                <label class="form-check-label fw-semibold" for="isActive">Active</label>
            </div>
        </div>

        <div class="d-flex gap-2">
            <button type="submit" class="btn btn-erp flex-fill">
                <i class="bi bi-<?= $isEdit?'check-lg':'plus-circle-fill' ?> me-2"></i>
                <?= $isEdit ? 'Update Consumer' : 'Add Consumer' ?>
            </button>
            <a href="<?= BASE_URL ?>/modules/admin/consumers.php" class="btn btn-outline-secondary">Cancel</a>
        </div>
    </form>
</div>

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