<?php
require_once '../config/db_config.php';
$conn = getDbConnection();
if (!$conn) {
    die("Connection failed: Database not found");
}

// Ambil data dari form
$email = $_POST['email'];
$raw_password = $_POST['password'];

try {
    $stmt = $conn->prepare("SELECT * FROM users WHERE email = :email LIMIT 1");
    $stmt->bindParam(':email', $email);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($user && password_verify($raw_password, $user['password'])) {
        session_start();
        $_SESSION['user_id'] = $user['user_id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION['name'] = $user['name'];
        $_SESSION['role'] = $user['role'];
        header('Location: dashboard.php');
        exit;
    } else {
        echo "<h2>Email atau password salah</h2>";
        echo "<p><a href='login.php'>Kembali ke login</a></p>";
    }
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
?>
