<?php
session_start();
include '../config.php';

$email    = $_POST['email'];
$password = $_POST['password'];

// Debug log
error_log("Login attempt for email: " . $email);

$query = "SELECT * FROM pengguna WHERE email='$email' AND peran='pelanggan'";
$result = mysqli_query($conn, $query);

if (mysqli_num_rows($result) == 1) {
    $user = mysqli_fetch_assoc($result);
    if (password_verify($password, $user['password'])) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['nama']    = $user['nama'];
        $_SESSION['peran']   = $user['peran'];

        // Debug: Log session data
        error_log("Login berhasil - User ID: " . $user['id'] . ", Nama: " . $user['nama']);

        // Simpan session dan redirect
        session_write_close();
        header("Location: ../index.php");
        exit();
    } else {
        error_log("Password salah untuk email: " . $email);
        header("Location: ../login.php?pesan=gagal");
        exit();
    }
} else {
    error_log("User tidak ditemukan atau bukan pelanggan: " . $email);
    header("Location: ../login.php?pesan=gagal");
    exit();
}
