<?php
session_start();
require '../config/database.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_logged_in']) || $_SESSION['role'] !== 'siswa') {
    echo json_encode(['success' => false, 'message' => 'Sesi berakhir']); exit;
}

$id_siswa = $_SESSION['id_user'];
$action = $_POST['action'] ?? '';

try {
    // Ambil data user saat ini untuk verifikasi lama
    $stmt = $pdo->prepare("SELECT password, pin FROM siswa WHERE id_siswa = ?");
    $stmt->execute([$id_siswa]);
    $user = $stmt->fetch();

    if ($action === 'password') {
        if (!password_verify($_POST['pass_lama'], $user['password'])) {
            echo json_encode(['success' => false, 'message' => 'Password lama salah!']); exit;
        }
        if ($_POST['pass_baru'] !== $_POST['pass_konf']) {
            echo json_encode(['success' => false, 'message' => 'Konfirmasi password tidak cocok!']); exit;
        }
        
        $hashed = password_hash($_POST['pass_baru'], PASSWORD_DEFAULT);
        $pdo->prepare("UPDATE siswa SET password = ? WHERE id_siswa = ?")->execute([$hashed, $id_siswa]);
        // Update tabel users juga agar login sinkron
        $pdo->prepare("UPDATE users SET password = ? WHERE username = ?")->execute([$hashed, $_SESSION['username']]);
        
        echo json_encode(['success' => true, 'message' => 'Password berhasil diganti']);

    } elseif ($action === 'pin') {
        if ($_POST['pin_lama'] !== $user['pin']) {
            echo json_encode(['success' => false, 'message' => 'PIN lama salah!']); exit;
        }
        if ($_POST['pin_baru'] !== $_POST['pin_konf']) {
            echo json_encode(['success' => false, 'message' => 'Konfirmasi PIN tidak cocok!']); exit;
        }
        if (strlen($_POST['pin_baru']) != 6) {
            echo json_encode(['success' => false, 'message' => 'PIN harus 6 digit!']); exit;
        }

        $pdo->prepare("UPDATE siswa SET pin = ? WHERE id_siswa = ?")->execute([$_POST['pin_baru'], $id_siswa]);
        echo json_encode(['success' => true, 'message' => 'PIN berhasil diganti']);
    }
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error']);
}