<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { http_response_code(200); exit(); }
error_reporting(0); 
require_once '../config/database.php';

$data = json_decode(file_get_contents("php://input"));

if(!empty($data->username) && !empty($data->tipe) && !empty($data->foto)) {
    date_default_timezone_set('Asia/Jakarta');
    
    // 1. Cari user_id dari tabel users (Sesuai maunya Web Admin)
    $stmtUser = $pdo->prepare("SELECT id FROM users WHERE username = ?");
    $stmtUser->execute([$data->username]);
    $user = $stmtUser->fetch();
    
    if (!$user) {
        echo json_encode(["status"=>"error", "message"=>"User tidak terdaftar di Web!"]);
        exit;
    }
    $user_id = $user['id'];
    $waktu = date('Y-m-d H:i:s');
    
    // Web Admin pakai tulisan 'in' dan 'out', bukan 'masuk' / 'pulang'
    $db_type = ($data->tipe == 'masuk') ? 'in' : 'out';

    // 2. Cek apakah hari ini sudah absen (Biar nggak dobel)
    $stmtCek = $pdo->prepare("SELECT id FROM attendance WHERE user_id = ? AND type = ? AND DATE(attendance_time) = CURDATE()");
    $stmtCek->execute([$user_id, $db_type]);
    if ($stmtCek->fetch()) {
        echo json_encode(["status"=>"error", "message"=>"Bos sudah absen " . strtoupper($data->tipe) . " hari ini!"]);
        exit;
    }

    // 3. Simpan foto ke folder khusus Web Admin
    $path_folder = '../assets/img/attendance/';
    if (!file_exists($path_folder)) {
        mkdir($path_folder, 0777, true);
    }
    $nama_foto = $data->username . '_' . $db_type . '_' . time() . '.jpg';
    $path_foto = $path_folder . $nama_foto;

    if(!file_put_contents($path_foto, base64_decode($data->foto))) {
        echo json_encode(["status"=>"error", "message"=>"Gagal menyimpan foto ke server!"]);
        exit;
    }

    // 4. Masukkan data ke tabel "attendance"
    $ins = $pdo->prepare("INSERT INTO attendance (user_id, attendance_time, type, photo, latitude, longitude) VALUES (?, ?, ?, ?, ?, ?)");
    $ins->execute([$user_id, $waktu, $db_type, $nama_foto, $data->lat, $data->long]);

    echo json_encode(["status"=>"success", "message"=>"✅ Absen berhasil masuk ke Web Admin!"]);
} else {
    echo json_encode(["status"=>"error", "message"=>"Data foto atau GPS tidak lengkap!"]);
}
?>