<?php
session_start();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $phone = htmlspecialchars($_POST['phone']);
    $pin = $_POST['pin'];

    // Koneksi ke database
    $mysqli = new mysqli("localhost", "wdpdev_master", "!Panda9980", "wdpdev_washing");

    if ($mysqli->connect_error) {
        die(json_encode(["success" => false, "error" => "Database connection failed."]));
    }

    // Mencari hash PIN dan ID pengguna berdasarkan nomor telepon
    $stmt = $mysqli->prepare("SELECT id, pin FROM users WHERE phone = ?");
    $stmt->bind_param("s", $phone);
    $stmt->execute();
    $stmt->bind_result($userId, $hashedPin);
    $stmt->fetch();

    // Verifikasi PIN
    if (password_verify($pin, $hashedPin)) {
        // Jika PIN benar, set session ID pengguna
        $_SESSION['user_id'] = $userId;

        // Redirect ke dashboard
        header('Location: dashboard.php');
        exit();
    } else {
        // Jika PIN salah, set pesan kesalahan dalam session dan redirect kembali
        $_SESSION['error'] = 'Incorrect PIN. Please try again.';
        header("Location: input_pin.php?phone=" . urlencode($phone));
        exit();
    }

    $stmt->close();
    $mysqli->close();
}
?>

