// KUMPULAN KODE BACKEND TERINTEGRASI IOT - SMART DOOR FTM ROOM FIBERID

// === DASHBOARD.PHP (Status ESP32, Pintu, WiFi Config, Notifikasi) ===
<?php
include 'koneksi.php';
$stmt = $pdo->query("SELECT count(*) as total_occupant FROM occupant WHERE status = 'approved'");
$total_occupant = $stmt->fetch()['total_occupant'];
$stmt = $pdo->query("SELECT count(*) as total_account FROM account WHERE status = 'approved'");
$total_account = $stmt->fetch()['total_account'];
$stmtUser = $pdo->prepare("SELECT name, username, foto, finger_id, finger_device, status FROM account WHERE id_account = ?");
$stmtUser->execute([$_SESSION['user_id']]);
$dashUser = $stmtUser->fetch(PDO::FETCH_ASSOC);
$dashHasFinger = ($dashUser && !empty($dashUser['finger_id']));
$dashFingerDevice = ($dashUser && !empty($dashUser['finger_device'])) ? $dashUser['finger_device'] : '';
$pdo->exec("CREATE TABLE IF NOT EXISTS login_history (
    id_log INT AUTO_INCREMENT PRIMARY KEY,
    id_account INT NOT NULL,
    device_info VARCHAR(255),
    ip_address VARCHAR(50),
    login_time DATETIME DEFAULT CURRENT_TIMESTAMP
)");
$stmtLastLog = $pdo->prepare("SELECT * FROM login_history WHERE id_account = ? ORDER BY login_time DESC LIMIT 1 OFFSET 1");
$stmtLastLog->execute([$_SESSION['user_id']]);
$lastLog = $stmtLastLog->fetch(PDO::FETCH_ASSOC);
if ($lastLog) {
    $uaLog = strtolower($lastLog['device_info']);
    if (strpos($uaLog, 'windows') !== false) $lastLogDevice = 'Windows PC';
    elseif (strpos($uaLog, 'mac') !== false) $lastLogDevice = 'Mac OS PC';
    elseif (strpos($uaLog, 'android') !== false) $lastLogDevice = 'Android Device';
    elseif (strpos($uaLog, 'iphone') !== false || strpos($uaLog, 'ipad') !== false) $lastLogDevice = 'iOS Device';
    elseif (strpos($uaLog, 'linux') !== false) $lastLogDevice = 'Linux PC';
    $tLog = strtotime($lastLog['login_time']);
    $lastLogTime = date('H:i:s', $tLog);
    $lastLogDesc = date('l, d F Y', $tLog);
}
?>

// JS: Scan WiFi ESP32
$('#btnScanWifi').on('click', function() {
    $('#wifiScanModal').modal('show');
    $.get('http://' + espIp + '/scan', function(data) {
        data.networks.forEach(function(net) {
            $('#wifiListItems').append('<div>' + net.ssid + ' (' + net.rssi + ' dBm)</div>');
        });
    });
});

// JS: Simpan WiFi Baru ke ESP32
$('#saveWifiBtn').on('click', function() {
    var ssid = $('#new-ssid').val();
    var pass = $('#new-wifi-pass').val();
    $.post('http://' + espIp + '/save', { ssid: ssid, pass: pass }, function(res) {
        // ESP32 restart & connect ke WiFi baru
    });
});

// JS: Notifikasi Real-Time
if (Notification.permission !== 'granted') {
    Notification.requestPermission();
}

// === ACCESS.PHP (Kontrol Akses Occupant & Pintu IoT) ===
<?php
$stmt = $pdo->query("SELECT * FROM occupant WHERE status = 'approved' ORDER BY id_occupant ASC");
$occupants = $stmt->fetchAll();
$no = 1;
foreach($occupants as $row):
    $sc = ($no % 2 == 1) ? 'row-odd' : 'row-even';
    $isVerified = !empty($row['name']) && !empty($row['nik_nip']) && !empty($row['no_hp'])
        && !empty($row['pin']) && !empty($row['foto']) && !empty($row['finger_id'])
        && $row['finger_id'] !== '-' && !empty($row['code_register'])
        && $row['progress'] === 'used' && $row['status'] === 'approved' && $row['access'] === 'active';
    $no++;
endforeach;
?>

// JS: Update Akses Occupant (Active/Pending/Suspend)
$('.btn-confirm-access').on('click', function() {
    var idOccupant = $(this).data('id');
    var accessValue = $('.access-dropdown[data-id="'+idOccupant+'"]').val();
    $.ajax({
        url: 'update_access_occupant.php',
        type: 'POST',
        dataType: 'json',
        data: { id_occupant: idOccupant, access: accessValue },
        success: function(response) {
            if(response.status === 'success') {
                originalAccessValues[idOccupant] = accessValue;
                showCustomAlert('Access successfully updated to ' + accessValue);
            } else {
                showCustomAlert(response.message || 'Failed to update access.');
                selectElement.val(originalAccessValues[idOccupant]);
            }
        },
        error: function() {
            selectElement.val(originalAccessValues[idOccupant]);
            showCustomAlert('Connection failed!');
        }
    });
});

// JS: Verifikasi PIN -> Unlock Pintu IoT
$('#btnSubmitPinAccess').on('click', function() {
    var pin = $('#accessPinInput').val();
    if (pin.length !== 6) {
        $('#verifyPinErrorMsg').text("Please enter your complete 6-digit PIN.");
        $('#verifyPinError').css('display', 'block');
        return;
    }
    var btn = $(this);
    btn.prop('disabled', true).html('<i class="mdi mdi-loading mdi-spin"></i> Verifying...');
    $.ajax({
        url: 'verify_any_pin.php',
        type: 'POST',
        dataType: 'json',
        data: { pin: pin },
        success: function(response) {
            btn.prop('disabled', false).html(origHtml);
            if (response.status === 'success') {
                $('#modalVerifyPin').modal('hide');
                setTimeout(function() { setGlobalDoorUnlocked(response.name); }, 400);
            } else {
                $('#verifyPinErrorMsg').text(response.message);
                $('#verifyPinError').css('display', 'block');
                $('#accessPinInput').val('').focus();
            }
        },
        error: function() {
            btn.prop('disabled', false).html(origHtml);
            $('#verifyPinErrorMsg').text("A network error occurred.");
            $('#verifyPinError').css('display', 'block');
        }
    });
});

// JS: Unlock/Lock Pintu IoT via API
function setGlobalDoorUnlocked(name) {
    $.post('api_door_status.php', { action: 'unlock' }, function(d) {
        if(d.status === 'success') {
            closeFpModal();
            setTimeout(function() {
                showDoorUnlockedModal(name);
                updateUIFromState('unlocked');
            }, 300);
        }
    }, 'json');
}
function setGlobalDoorLocked() {
    $.post('api_door_status.php', { action: 'lock' }, function(d) {
        if(d.status === 'success') {
            showCustomAlert('Door locked successfully!');
            closeDoorModal();
            updateUIFromState('locked');
        }
    }, 'json');
}

// JS: Handle tombol UNLOCK/LOCK
$('#btnOpenDoor').on('click', function() {
    if (window.isDoorUnlocked) {
        setGlobalDoorLocked();
    } else {
        $('#accessPinInput').val('');
        $('#verifyPinError').css('display', 'none');
        $('#modalVerifyPin').modal('show');
        setTimeout(() => $('#accessPinInput').focus(), 500);
    }
});

// JS: WebAuthn Biometrik (Sidik Jari Browser)
async function startWebAuthnVerification() {
    if (!window.PublicKeyCredential) {
        showScanResult('error', 'Not Supported', 'Your browser does not support biometric unlock.');
        return;
    }
    try {
        const challenge = new Uint8Array(32);
        window.crypto.getRandomValues(challenge);
        const publicKey = {
            challenge: challenge,
            rpId: window.location.hostname,
            userVerification: "required",
            timeout: 60000
        };
        const credential = await navigator.credentials.get({ publicKey });
        if (!credential) throw new Error("No fingerprint detected");
        const rawIdBase64 = btoa(String.fromCharCode.apply(null, new Uint8Array(credential.rawId)));
        showVerifyingState();
        verifyFingerprintServer(rawIdBase64);
    } catch (err) {
        showScanResult('error', 'Cancelled', 'Door unlock was cancelled.');
    }
}

function verifyFingerprintServer(credentialId) {
    $.ajax({
        url: 'verify_door_fingerprint.php',
        type: 'POST',
        dataType: 'json',
        data: { credential_id: credentialId },
        success: function(response) {
            if(response.status === 'success') {
                setGlobalDoorUnlocked(response.name);
            } else {
                showScanResult('error', 'Unlock Failed', response.message || 'Not authorized.');
            }
        },
        error: function() {
            showScanResult('error', 'Connection Lost', 'Unable to reach the server.');
        }
    });
}

// JS: Polling Status Pintu Setiap 2.5 Detik
window.isDoorUnlocked = false;
function pollDoorStatus() {
    $.get('api_door_status.php', function(data) {
        if (data && data.status === 'success') {
            updateUIFromState(data.door_state);
        }
    }, 'json');
}
setInterval(pollDoorStatus, 2500);
pollDoorStatus();

// JS: Update UI Pintu (locked/unlocked)
function updateUIFromState(state) {
    if (state === 'unlocked') {
        window.isDoorUnlocked = true;
        $('#btnOpenDoor').removeClass('btn-primary').addClass('btn-danger').css('box-shadow', 'none');
        $('#btnOpenDoor .btn-text').html('<i class="mdi mdi-lock mr-2" style="font-size: 20px;"></i> LOCK DOOR');
        $('#doorIcon').removeClass('mdi-door-closed').addClass('mdi-door-open');
        if (!$('#doorModal').is(':visible')) openDoorModal();
    } else {
        window.isDoorUnlocked = false;
        $('#btnOpenDoor').removeClass('btn-danger').addClass('btn-primary').css('box-shadow', '');
        $('#btnOpenDoor .btn-text').html('<i class="mdi mdi-key mr-2" style="font-size: 20px;"></i> UNLOCK DOOR');
        $('#doorIcon').removeClass('mdi-door-open').addClass('mdi-door-closed');
        if ($('#doorModal').is(':visible')) closeDoorModal();
    }
}

// JS: Lock dari Modal
$(document).on('click', '#btnLockDoor', function() { setGlobalDoorLocked(); });

// === MANAGE_OCCUPANT.PHP (Kelola Data Biometrik Occupant) ===
<?php
$stmt = $pdo->query("SELECT * FROM occupant WHERE status = 'approved' ORDER BY id_occupant ASC");
$occupants = $stmt->fetchAll();
$no = 1;
foreach($occupants as $row):
    $isChecked = ($row['status'] === 'approved') ? 'checked' : '';
    $fotoSrc = (!empty($row['foto']) && file_exists($row['foto'])) ? $row['foto'] : 'images/faces/user.jpg';
    $hasFoto = (!empty($row['foto']) && file_exists($row['foto'])) ? '1' : '0';
    $codeRaw = $row['code_register'];
    $codeDisplay = htmlspecialchars($codeRaw);
    if ($row['progress'] === 'used' && strlen($codeRaw) > 10)
        $codeDisplay = htmlspecialchars(substr($codeRaw, 0, 24)) . '...';
    // Enkripsi fingerprint ID (SHA-256, 9 karakter)
    $fingerId = (isset($row['finger_id']) && $row['finger_id'] !== '-')
        ? substr(hash('sha256', $row['finger_id']), 0, 9) : '';
    $fingerOk = (isset($row['finger_id']) && trim($row['finger_id']) !== ''
        && $row['finger_id'] !== '0' && $row['finger_id'] !== '-'
        && strtolower(trim($row['finger_id'])) !== 'null');
    $sc = ($no % 2 == 1) ? 'row-odd' : 'row-even';
    $isVerified = !empty($row['name']) && !empty($row['nik_nip']) && !empty($row['no_hp'])
        && !empty($row['pin']) && !empty($row['foto']) && !empty($row['finger_id'])
        && $row['finger_id'] !== '-' && !empty($row['code_register'])
        && $row['progress'] === 'used' && $row['status'] === 'approved' && $row['access'] === 'active';
    $no++;
endforeach;
?>

// === NEW_OCCUPANT.PHP (Registrasi Penghuni Baru) ===
<?php
$stmt = $pdo->query("SELECT * FROM occupant WHERE status = 'rejected' ORDER BY id_occupant ASC");
$occupants = $stmt->fetchAll();
$no = 1;
foreach ($occupants as $row):
    $fotoSrc = (!empty($row['foto']) && file_exists($row['foto'])) ? $row['foto'] : 'images/faces/user.jpg';
    $hasFoto = (!empty($row['foto']) && file_exists($row['foto'])) ? '1' : '0';
    $codeRaw = $row['code_register'];
    $codeDisplay = htmlspecialchars($codeRaw);
    if ($row['progress'] === 'used' && strlen($codeRaw) > 10)
        $codeDisplay = htmlspecialchars(substr($codeRaw, 0, 24)) . '...';
    $fingerId = !empty($row['finger_id']) ? htmlspecialchars($row['finger_id']) : '';
    $fingerOk = !empty($row['finger_id']);
    $sc = ($no % 2 == 1) ? 'row-odd' : 'row-even';
    $no++;
endforeach;
?>

// === ROOM.PHP (Jadwal Pembatasan Akses Ruangan) ===
<?php
include 'koneksi.php';
$pdo->exec("CREATE TABLE IF NOT EXISTS room_restrictions (
    id_restriction INT AUTO_INCREMENT PRIMARY KEY,
    day_of_week VARCHAR(20) NOT NULL,
    time_from TIME NOT NULL,
    time_to TIME NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
$stmt = $pdo->query("SELECT * FROM room_restrictions ORDER BY FIELD(day_of_week,
    'Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday','Every Day'), time_from ASC");
$restrictions = $stmt->fetchAll();
if (!empty($restrictions)):
    $no = 1;
    foreach ($restrictions as $row):
        $sc = ($no % 2 == 1) ? 'row-odd' : 'row-even';
        $dayLabel = $row['day_of_week'];
        if ($dayLabel === 'Every Day') $dayLabel = 'Every Day (*)';
        $no++;
    endforeach;
endif;
?>

// === NEW_ACCOUNT.PHP (Registrasi Akun Admin Baru) ===
<?php
$stmt = $pdo->query("SELECT * FROM account WHERE status = 'rejected' ORDER BY id_account ASC");
$accounts = $stmt->fetchAll();
$no = 1;
foreach ($accounts as $row):
    $isChecked = ($row['status'] === 'approved') ? 'checked' : '';
    $sc = ($no % 2 == 1) ? 'row-odd' : 'row-even';
    $no++;
endforeach;
// Ambil fingerprint ID yang sudah terdaftar (cegah duplikasi biometrik)
$stmtEx = $pdo->query("SELECT finger_id FROM account WHERE finger_id IS NOT NULL AND finger_id != ''");
$allCredsArray = $stmtEx->fetchAll(PDO::FETCH_COLUMN);
?>

// === OPERATIONS_ACCOUNT.PHP (Kelola Akun Admin Aktif) ===
<?php
$stmt = $pdo->query("SELECT * FROM account WHERE status = 'approved' ORDER BY id_account ASC");
$accounts = $stmt->fetchAll();
$no = 1;
foreach ($accounts as $row):
    $isChecked = ($row['status'] === 'approved') ? 'checked' : '';
    $fotoSrc = (!empty($row['foto']) && file_exists($row['foto'])) ? $row['foto'] : 'images/faces/user.jpg';
    $hasFoto = (!empty($row['foto']) && file_exists($row['foto'])) ? '1' : '0';
    $fingerId = !empty($row['finger_id']) ? htmlspecialchars($row['finger_id']) : '';
    $fingerOk = !empty($row['finger_id']);
    $sc = ($no % 2 == 1) ? 'row-odd' : 'row-even';
    $isCurrentUser = (isset($_SESSION['user_id']) && $row['id_account'] == $_SESSION['user_id']);
    $no++;
endforeach;
$stmtEx = $pdo->query("SELECT finger_id FROM account WHERE finger_id IS NOT NULL AND finger_id != ''");
$allCredsArray = $stmtEx->fetchAll(PDO::FETCH_COLUMN);
?>

// === HISTORY.PHP (Log Kegiatan Ruangan + Auto-Cleanup) ===
<?php
include 'koneksi.php';
try {
    $pdo->exec("ALTER TABLE history
        ADD COLUMN is_read TINYINT(1) DEFAULT 0,
        ADD COLUMN is_starred TINYINT(1) DEFAULT 0,
        ADD COLUMN is_deleted TINYINT(1) DEFAULT 0,
        ADD COLUMN occupant_name VARCHAR(255) DEFAULT NULL,
        ADD COLUMN deleted_at DATETIME DEFAULT NULL");
} catch (PDOException $e) {}
try {
    $pdo->exec("DROP TRIGGER IF EXISTS trg_history_occupant_delete");
    $pdo->exec("
        CREATE TRIGGER trg_history_occupant_delete
        BEFORE DELETE ON occupant FOR EACH ROW
        BEGIN
            UPDATE history SET occupant_name = OLD.name, is_deleted = 1,
                is_starred = 0, is_read = 1, deleted_at = IFNULL(deleted_at, NOW())
            WHERE occupant_id = OLD.id_occupant;
        END
    ");
    // Auto-delete trash > 30 hari
    $oldHistories = $pdo->query("SELECT id_history, schedule_id FROM history
        WHERE is_deleted = 1 AND deleted_at < DATE_SUB(NOW(), INTERVAL 30 DAY)")->fetchAll(PDO::FETCH_ASSOC);
    if (!empty($oldHistories)) {
        $delHistIds = array_column($oldHistories, 'id_history');
        if (!empty($delHistIds)) {
            $inQueryHist = implode(',', array_fill(0, count($delHistIds), '?'));
            $pdo->prepare("DELETE FROM history WHERE id_history IN ($inQueryHist)")->execute($delHistIds);
        }
        $delSchedIds = array_column($oldHistories, 'schedule_id');
        if (!empty($delSchedIds)) {
            $inQuerySched = implode(',', array_fill(0, count($delSchedIds), '?'));
            $pdo->prepare("DELETE FROM schedule WHERE id_schedule IN ($inQuerySched)")->execute($delSchedIds);
        }
    }
} catch (PDOException $e) {}
$limit = 12;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$searchQuery = "";
$searchParams = [];
$folderCondition = "h.is_deleted = 0";
if (!empty($search)) {
    $searchQuery .= " AND (COALESCE(o.name, h.occupant_name) LIKE ? OR o.nik_nip LIKE ? OR o.no_hp LIKE ? OR s.kegiatan LIKE ?)";
    $searchParamValue = "%$search%";
    $searchParams = array_merge($searchParams, [$searchParamValue, $searchParamValue, $searchParamValue, $searchParamValue]);
}
$stmtTotal = $pdo->prepare("SELECT COUNT(*) FROM history h
    LEFT JOIN occupant o ON h.occupant_id = o.id_occupant
    JOIN schedule s ON h.schedule_id = s.id_schedule
    WHERE $folderCondition $searchQuery");
$stmtTotal->execute($searchParams);
$totalData = $stmtTotal->fetchColumn();
$totalPages = ceil($totalData / $limit);
$query = "SELECT h.id_history, h.foto AS history_foto, h.is_read, h.is_starred, h.is_deleted, h.occupant_name,
    o.name, o.nik_nip, o.no_hp, o.foto AS occupant_foto, s.date AS schedule_date, s.kegiatan
    FROM history h LEFT JOIN occupant o ON h.occupant_id = o.id_occupant
    JOIN schedule s ON h.schedule_id = s.id_schedule
    WHERE $folderCondition $searchQuery ORDER BY s.date DESC LIMIT $limit OFFSET $offset";
$stmt = $pdo->prepare($query);
$stmt->execute($searchParams);
$histories = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($histories as $idx => $h):
    $timestamp = strtotime($h['schedule_date']);
    $timeDate = date('M d, Y • h:i A', $timestamp);
    $dispName = !empty($h['name']) ? $h['name'] : (!empty($h['occupant_name']) ? $h['occupant_name'] : 'Deleted Occupant');
    $dispFoto = !empty($h['occupant_foto']) ? $h['occupant_foto'] : 'images/admin.png';
    $dispNik = !empty($h['nik_nip']) ? $h['nik_nip'] : '-';
    $dispHp = !empty($h['no_hp']) ? $h['no_hp'] : '-';
    $mainImg = !empty($h['history_foto']) ? $h['history_foto'] : 'images/placeholder.jpg';
    $jsonData = htmlspecialchars(json_encode([
        'id' => $h['id_history'], 'name' => $dispName, 'nik' => $dispNik, 'hp' => $dispHp,
        'kegiatan' => $h['kegiatan'], 'time' => $timeDate, 'img' => $mainImg,
        'avatar' => $dispFoto, 'is_read' => $h['is_read']
    ]), ENT_QUOTES, 'UTF-8');
endforeach;
// Pagination
$maxVisible = 5;
$startPage = max(1, $page - floor($maxVisible / 2));
$endPage = min($totalPages, $startPage + $maxVisible - 1);
if ($endPage - $startPage + 1 < $maxVisible)
    $startPage = max(1, $endPage - $maxVisible + 1);
?>

// JS: Mark as Read & Delete History
function openHistoryDetail(data) {
    $('#modalDetailHistory').modal('show');
    if (data.is_read == 0) {
        $.post('history_ajax.php', { action: 'mark_read', id: data.id }, function(res) {
            if (res.status === 'success') {
                let dot = document.getElementById('unread-' + data.id);
                if(dot) { dot.style.opacity = "0"; setTimeout(() => dot.remove(), 300); }
                data.is_read = 1;
            }
        });
    }
}
function deleteHistory(id) {
    $.post('history_ajax.php', { action: 'hard_delete', id: id }, function(res) {
        if (res.status === 'success') {
            $('#modalDeleteHistory').modal('hide');
            $(`.history-card[data-id="${id}"]`).fadeOut(300, function() {
                $(this).remove();
                if($('.history-card').length === 0) window.location.reload();
            });
        }
    }, 'json');
}

// === SCHEDULE.PHP (Kalender Kegiatan + API Offline Report ESP32) ===
<?php
// API: ESP32 mengirim laporan kegiatan offline saat reconnect
if (isset($_GET['action']) && $_GET['action'] == 'offline_report') {
    include_once 'koneksi.php';
    date_default_timezone_set('Asia/Jakarta');
    $data = json_decode(file_get_contents('php://input'), true);
    if ($data && isset($data['activity'])) {
        $activity = trim($data['activity']);
        if (!empty($activity)) {
            $stmt = $pdo->prepare("INSERT INTO schedule (date, kegiatan) VALUES (NOW(), ?)");
            $stmt->execute([$activity]);
        }
    }
    echo json_encode(["status" => "success"]);
    exit;
}
include_once 'koneksi.php';
date_default_timezone_set('Asia/Jakarta');
$pdo->exec("CREATE TABLE IF NOT EXISTS schedule (
    id_schedule INT AUTO_INCREMENT PRIMARY KEY,
    date TIMESTAMP NOT NULL,
    kegiatan VARCHAR(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
$month = isset($_GET['m']) ? (int)$_GET['m'] : (int)date('m');
$year  = isset($_GET['y']) ? (int)$_GET['y'] : (int)date('Y');
if($month < 1){ $month = 12; $year--; }
if($month > 12){ $month = 1; $year++; }
$firstDay = mktime(0,0,0,$month,1,$year);
$daysInMonth = (int)date('t', $firstDay);
$startWeekday = (int)date('w', $firstDay);
$today = date('Y-m-d');
$pm = $month-1; $py = $year; if($pm<1){$pm=12;$py--;}
$nm = $month+1; $ny = $year; if($nm>12){$nm=1;$ny++;}
$stmt = $pdo->prepare("SELECT * FROM schedule WHERE MONTH(date)=? AND YEAR(date)=? ORDER BY date ASC");
$stmt->execute([$month, $year]);
$rows = $stmt->fetchAll();
$eventsByDate = [];
foreach($rows as $r) {
    $d = substr($r['date'], 0, 10);
    if(!isset($eventsByDate[$d])) $eventsByDate[$d] = [];
    $eventsByDate[$d][] = $r;
}
$activities = $rows;
?>
