<?php
// === HEADER CORS & JSON RESPONSE ===
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
header('Content-Type: application/json; charset=UTF-8');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

require_once "db_config.php";

function send_json($data) {
    echo json_encode($data);
    exit;
}

// === DETEKSI AKSI ===
$method = $_SERVER['REQUEST_METHOD'];
$contentType = $_SERVER['CONTENT_TYPE'] ?? '';

if ($method === 'POST' && strpos($contentType, 'multipart/form-data') !== false) {
    $aksi = $_POST['aksi'] ?? null;
    $postjson = $_POST;
} else {
    $postjson = json_decode(file_get_contents("php://input"), true);
    $aksi = $postjson['aksi'] ?? null;
}

if (!$aksi) {
    send_json(['success' => false, 'msg' => '❗ Parameter aksi tidak ditemukan']);
}

try {
    switch ($aksi) {

        // === LOGIN MAHASISWA ===
        case 'login':
            $nim = trim($postjson['nim'] ?? '');
            $password = trim($postjson['password'] ?? '');
            if (!$nim || !$password) {
                send_json(['success' => false, 'msg' => '❗ NIM dan Password wajib diisi.']);
            }

            $stmt = $pdo->prepare("SELECT * FROM mahasiswa WHERE nim = ?");
            $stmt->execute([$nim]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($user && $user['password'] === $password) {
                send_json(['success' => true, 'msg' => '✅ Login berhasil!', 'user' => $user]);
            } else {
                send_json(['success' => false, 'msg' => '❌ NIM atau Password salah.']);
            }
            break;

        // === LOGIN DOSEN ===
        case 'login_dosen':
            $nidn = trim($postjson['nidn'] ?? '');
            $password = trim($postjson['password'] ?? '');
            if (!$nidn || !$password) {
                send_json(['success' => false, 'msg' => '❗ NIDN dan Password wajib diisi.']);
            }

            $stmt = $pdo->prepare("SELECT * FROM dosen WHERE nidn = ?");
            $stmt->execute([$nidn]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($user && $user['password'] === $password) {
                send_json(['success' => true, 'msg' => '✅ Login dosen berhasil!', 'user' => $user]);
            } else {
                send_json(['success' => false, 'msg' => '❌ NIDN atau Password salah.']);
            }
            break;

        // === TAMBAH ABSENSI ===
        case 'tambah_absensi':
            $data = $postjson;

            if (empty($data['nama']) || empty($data['nim']) || empty($data['prodi']) ||
                empty($data['tanggal']) || empty($data['jam_masuk']) || empty($data['jam_keluar']) || empty($data['status'])) {
                send_json(['success' => false, 'msg' => '❗ Lengkapi semua data wajib.']);
            }

            $bukti_url = '';
            if (!empty($data['bukti']) && preg_match('/^data:image\/(\w+);base64,/', $data['bukti'], $type)) {
                $data['bukti'] = base64_decode(substr($data['bukti'], strpos($data['bukti'], ',') + 1));
                if ($data['bukti'] === false) {
                    send_json(['success' => false, 'msg' => '❌ Gagal decode gambar bukti']);
                }

                $ext = strtolower($type[1]);
                if (!in_array($ext, ['jpg', 'jpeg', 'png'])) {
                    send_json(['success' => false, 'msg' => '❌ Format gambar tidak didukung']);
                }

                $folder = "uploads/";
                if (!is_dir($folder)) mkdir($folder, 0777, true);

                $filename = 'absensi_' . time() . '_' . rand(100, 999) . '.' . $ext;
                $filepath = $folder . $filename;
                file_put_contents($filepath, $data['bukti']);

                $bukti_url = "http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/" . $filepath;
            }

            $stmt = $pdo->prepare("INSERT INTO absensi (nama, nim, prodi, tanggal, jam_masuk, jam_keluar, keterangan, status, bukti)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $simpan = $stmt->execute([
                $data['nama'], $data['nim'], $data['prodi'], $data['tanggal'],
                $data['jam_masuk'], $data['jam_keluar'], $data['keterangan'] ?? '', $data['status'], $bukti_url
            ]);

            send_json(['success' => $simpan, 'msg' => $simpan ? '✅ Absensi disimpan' : '❌ Gagal simpan absensi']);
            break;

        // === GET ABSENSI ===
        case 'get_absensi':
            $stmt = $pdo->prepare("SELECT * FROM absensi ORDER BY tanggal DESC, jam_masuk DESC");
            $stmt->execute();
            $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
            send_json(['success' => true, 'result' => $data]);
            break;

        // === UNGGAH LAPORAN ===
// === UNGGAH LAPORAN ===
case 'unggah_laporan':
    if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        send_json(['success' => false, 'msg' => '❌ File tidak valid']);
    }

    $keterangan = $_POST['keterangan'] ?? '';
    if (!$keterangan) {
        send_json(['success' => false, 'msg' => '❗ Keterangan wajib diisi']);
    }

    $folder = "laporan/";
    if (!is_dir($folder)) mkdir($folder, 0777, true);

    $originalName = basename($_FILES['file']['name']);
    $ext = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
    $allowed = ['pdf', 'doc', 'docx', 'png', 'jpg', 'jpeg'];

    if (!in_array($ext, $allowed)) {
        send_json(['success' => false, 'msg' => '❌ Format file tidak diperbolehkan']);
    }

    $filename = 'laporan_' . time() . '_' . rand(100, 999) . '.' . $ext;
    $targetPath = $folder . $filename;

    if (!move_uploaded_file($_FILES['file']['tmp_name'], $targetPath)) {
        send_json(['success' => false, 'msg' => '❌ Gagal menyimpan file']);
    }

    $file_url = "http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/' . $targetPath;

    $stmt = $pdo->prepare("INSERT INTO laporan (keterangan, file_url, tanggal_upload, status_verifikasi)
        VALUES (?, ?, NOW(), 'Menunggu')");
    $simpan = $stmt->execute([$keterangan, $file_url]);

    send_json(['success' => $simpan, 'file_url' => $file_url, 'msg' => $simpan ? '✅ Laporan berhasil diunggah' : '❌ Gagal simpan laporan']);
    break;


        // === RIWAYAT LAPORAN ===
        case 'riwayat_laporan_mahasiswa':
            $stmt = $pdo->prepare("SELECT * FROM laporan ORDER BY tanggal_upload DESC");
            $stmt->execute();
            $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
            foreach ($data as &$item) {
                if (!empty($item['file_url']) && !preg_match('/^http/', $item['file_url'])) {
                    $item['file_url'] = "http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/' . $item['file_url'];
                }
            }
            send_json(['success' => true, 'result' => $data]);
            break;

        // === VERIFIKASI LAPORAN ===
        case 'verifikasi_laporan':
            $id = $postjson['id'] ?? null;
            if (!$id) send_json(['success' => false, 'msg' => '❗ ID laporan kosong']);

            $stmt = $pdo->prepare("UPDATE laporan SET status_verifikasi = 'Terverifikasi', catatan = NULL WHERE id = ?");
            $update = $stmt->execute([$id]);
            send_json(['success' => $update, 'msg' => $update ? '✅ Laporan diverifikasi' : '❌ Gagal verifikasi']);
            break;

        // === TOLAK LAPORAN ===
        case 'tolak_laporan':
            $id = $postjson['id'] ?? null;
            $catatan = $postjson['catatan'] ?? '';
            if (!$id) send_json(['success' => false, 'msg' => '❗ ID laporan kosong']);

            $stmt = $pdo->prepare("UPDATE laporan SET status_verifikasi = 'Ditolak', catatan = ? WHERE id = ?");
            $update = $stmt->execute([$catatan, $id]);
            send_json(['success' => $update, 'msg' => $update ? '✅ Laporan ditolak' : '❌ Gagal tolak laporan']);
            break;

        // === HAPUS LAPORAN ===
        case 'hapus_laporan':
            $id = $postjson['id'] ?? null;
            if (!$id) send_json(['success' => false, 'msg' => '❗ ID tidak ditemukan']);

            $stmt = $pdo->prepare("SELECT file_url FROM laporan WHERE id = ?");
            $stmt->execute([$id]);
            $laporan = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($laporan && !empty($laporan['file_url'])) {
                $path = parse_url($laporan['file_url'], PHP_URL_PATH);
                $localPath = $_SERVER['DOCUMENT_ROOT'] . $path;
                if (file_exists($localPath)) {
                    unlink($localPath);
                }
            }

            $stmt = $pdo->prepare("DELETE FROM laporan WHERE id = ?");
            $hapus = $stmt->execute([$id]);
            send_json(['success' => $hapus, 'msg' => $hapus ? '✅ Laporan dihapus' : '❌ Gagal hapus']);
            break;

        // === RINGKASAN ABSENSI ===
        case 'get_absensi_summary':
            $nim = $postjson['nim'] ?? null;
            if (!$nim) send_json(['success' => false, 'msg' => '❗ NIM tidak ditemukan']);

            $stmt = $pdo->prepare("SELECT jam_masuk, jam_keluar, status FROM absensi WHERE nim = ?");
            $stmt->execute([$nim]);

            $hadir = 0;
            $alpha = 0;
            $totalJam = 0;

            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                if ($row['status'] === 'Hadir') $hadir++;
                if ($row['status'] === 'Alpha') $alpha++;

                if ($row['jam_masuk'] && $row['jam_keluar']) {
                    $masuk = strtotime("1970-01-01 " . $row['jam_masuk']);
                    $keluar = strtotime("1970-01-01 " . $row['jam_keluar']);
                    if ($keluar > $masuk) {
                        $totalJam += ($keluar - $masuk) / 3600;
                    }
                }
            }

            send_json([
                'success' => true,
                'totalHadir' => $hadir,
                'totalAlpha' => $alpha,
                'totalJam' => round($totalJam)
            ]);
            break;

        // === DEFAULT ===
        default:
            send_json(['success' => false, 'msg' => '❌ Aksi tidak dikenali']);
    }
} catch (PDOException $e) {
    send_json(['success' => false, 'msg' => '❌ DB Error: ' . $e->getMessage()]);
}
