<?php
// ======================================================================
// login.php (VERSI FINAL - KEMBALI KE RESPON JSON UNTUK FRONTEND JS)
// ======================================================================

// Pastikan session.save_path valid
$customSessionPath = '/home/rhlqyjgg/php_sessions';
if (!is_dir($customSessionPath)) {
    mkdir($customSessionPath, 0750, true);
}
ini_set('session.save_path', $customSessionPath);

// ======================================================================
// KONFIGURASI COOKIE SEBELUM session_start()!
// ======================================================================
// PENTING: Atur domain cookie agar berlaku untuk domain utama dan semua subdomain.
// Titik di depan nama domain sangat penting.
ini_set('session.cookie_domain', '.sumberbarokahsentosa.my.id'); 
ini_set('session.cookie_secure', 1); // Wajib 1 (true) karena Anda menggunakan HTTPS
ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_samesite', 'None'); // Wajib 'None' untuk cross-site cookies dengan Secure
ini_set('session.cookie_path', '/');
ini_set('session.gc_maxlifetime', 86400);

session_start();

// Log untuk verifikasi session (opsional, sangat direkomendasikan untuk debugging)
error_log("LOGIN_SCRIPT_START: Session ID: " . session_id());
error_log("LOGIN_SCRIPT_START: Current session: " . print_r($_SESSION, true));

// ======================================================================
// HEADER UNTUK CORS - Ini diperlukan jika frontend Anda di domain/subdomain lain
// ======================================================================
header("Access-Control-Allow-Origin: https://sumberbarokahsentosa.my.id"); // Sesuaikan jika frontend di domain/subdomain lain
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Content-Type: application/json; charset=UTF-8"); // Ini HARUS ADA lagi karena kita merespons JSON

// Tangani preflight request OPTIONS
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    session_write_close();
    http_response_code(204);
    exit;
}

// Pastikan hanya POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(["success" => false, "message" => "Metode tidak diizinkan"]);
    exit;
}

include "koneksi.php"; // Pastikan path ke koneksi.php benar

// Cek koneksi database
if (mysqli_connect_errno()) {
    error_log("LOGIN_ERROR: Koneksi database gagal - " . mysqli_connect_error());
    http_response_code(500);
    echo json_encode(["success" => false, "message" => "Kesalahan server: Koneksi database gagal"]);
    exit;
}

// Baca input JSON dari body request
$json = file_get_contents('php://input');
$input = json_decode($json, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    http_response_code(400);
    echo json_encode(["success" => false, "message" => "Format JSON tidak valid: " . json_last_error_msg()]);
    exit;
}

// Validasi input
if (empty($input['username']) || empty($input['password'])) {
    http_response_code(400);
    echo json_encode(["success" => false, "message" => "Username dan password wajib diisi"]);
    exit;
}

$username = mysqli_real_escape_string($conn, trim($input['username']));
$password = $input['password'];

// Validasi panjang username
if (strlen($username) > 50) {
    http_response_code(400);
    echo json_encode(["success" => false, "message" => "Username terlalu panjang"]);
    exit;
}

// Persiapkan query SQL
$sql = "SELECT id, username, password, role FROM user WHERE username = ? LIMIT 1";
$stmt = mysqli_prepare($conn, $sql);

if (!$stmt) {
    error_log("LOGIN_ERROR: Prepared statement failed - " . mysqli_error($conn));
    http_response_code(500);
    echo json_encode(["success" => false, "message" => "Kesalahan server: Gagal mempersiapkan query"]);
    exit;
}

mysqli_stmt_bind_param($stmt, "s", $username);

// Eksekusi query
if (!mysqli_stmt_execute($stmt)) {
    error_log("LOGIN_ERROR: Eksekusi statement gagal - " . mysqli_stmt_error($stmt));
    http_response_code(500);
    echo json_encode(["success" => false, "message" => "Kesalahan server: Gagal mengeksekusi query"]);
    mysqli_stmt_close($stmt);
    exit;
}

$result = mysqli_stmt_get_result($stmt);

if (!$result) {
    error_log("LOGIN_ERROR: Mendapatkan hasil query gagal - " . mysqli_error($conn));
    http_response_code(500);
    echo json_encode(["success" => false, "message" => "Kesalahan server: Gagal mendapatkan hasil query"]);
    mysqli_stmt_close($stmt);
    exit;
}

// Periksa hasil query
if (mysqli_num_rows($result) === 1) {
    $user = mysqli_fetch_assoc($result);

    // Verifikasi password
    if (password_verify($password, $user['password'])) {
        // LOGIN BERHASIL

        session_regenerate_id(true);
        
        // Set variabel session baru
        $_SESSION['loggedin'] = true;
        $_SESSION['userid']   = $user['id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION['role']     = $user['role'];
        
        error_log("LOGIN_SUCCESS: User {$user['username']} logged in with role {$user['role']}");
        error_log("LOGIN_SUCCESS: New Session ID: " . session_id());
        error_log("LOGIN_SUCCESS: Session data: " . print_r($_SESSION, true));
        
        // Siapkan respons JSON untuk frontend
        $response = [
            "success" => true,
            "message" => "Login berhasil",
            "role"    => $user['role'],
            "data"    => [
                "id" => $user['id'],
                "username" => $user['username']
            ],
            "session_id" => session_id()
        ];
        
        session_write_close(); 
        echo json_encode($response);
        
    } else {
        // Password salah
        error_log("LOGIN_FAIL: Password salah untuk: $username");
        http_response_code(401); // Unauthorized
        echo json_encode(["success" => false, "message" => "Username atau password salah"]);
    }
} else {
    // Username tidak ditemukan
    error_log("LOGIN_FAIL: Username tidak ditemukan: $username");
    http_response_code(401); // Unauthorized
    echo json_encode(["success" => false, "message" => "Username atau password salah"]);
}

// Tutup statement dan koneksi database
mysqli_stmt_close($stmt);
mysqli_close($conn);
exit;
?>