<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
require_once 'config.php';

// ডিবাগ: ফর্ম ডাটা দেখুন
// echo "<pre>"; print_r($_POST); echo "</pre>"; // টেস্ট করার জন্য আনকমেন্ট করুন

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: index.php");
    exit();
}

if (!isset($_POST['key']) || $_POST['key'] !== SECRET_KEY) {
    header("Location: index.php?error=2");
    exit();
}

$username = trim($_POST['username'] ?? '');
$password = $_POST['password'] ?? '';

if (empty($username) || empty($password)) {
    header("Location: index.php?error=1");
    exit();
}

try {
    // ইউজার খোঁজা (email বা username দিয়ে)
    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ? OR username = ?");
    $stmt->execute([$username, $username]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($user) {
        // ডিবাগ: ইউজার পাওয়া গেছে
        // echo "User found: " . $user['name']; 
        
        if (password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['name'] = $user['name'];
            $_SESSION['role'] = $user['role'] ?? 'user';
            
            header("Location: dashboard.php");
            exit();
        } else {
            // echo "Password incorrect";
            header("Location: index.php?error=1");
            exit();
        }
    } else {
        // echo "User not found";
        header("Location: index.php?error=1");
        exit();
    }
} catch (PDOException $e) {
    // echo "Error: " . $e->getMessage();
    header("Location: index.php?error=2");
    exit();
}
?>