<?php
session_start();

// Sertakan file config.php untuk koneksi database
include 'config.php';

// Cek apakah form telah disubmit
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Ambil data dari form
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Validasi data - pastikan semua field diisi
    if (empty($username) || empty($password)) {
        echo "Username and password are required!";
        exit;
    }

    // Siapkan SQL untuk mengambil data admin berdasarkan username
    $query = "SELECT * FROM admin_master WHERE username = :username";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':username', $username);
    $stmt->execute();

    // Periksa apakah username ditemukan
    if ($stmt->rowCount() > 0) {
        // Ambil data admin
        $admin = $stmt->fetch(PDO::FETCH_ASSOC);

        // Verifikasi password
        if (password_verify($password, $admin['password'])) {
            // Jika password benar, simpan data ke session
            $_SESSION['admin_id'] = $admin['id'];
            $_SESSION['username'] = $admin['username'];
            $_SESSION['role'] = $admin['role'];

            // Redirect ke halaman dashboard
            header("Location: dashboard.php");
            exit;
        } else {
            echo "Invalid password.";
        }
    } else {
        echo "Username not found.";
    }
}
?>
