<?php
require_once 'session_init.php';
require_once 'db.php';

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $identifier = trim($_POST['email_or_username'] ?? '');
    $password = trim($_POST['password'] ?? '');

    if (empty($identifier) || empty($password)) {
        header("Location: login.php?error=empty");
        exit();
    }

    $stmt = $conn->prepare("SELECT id, username, email, password_hash, role, is_verified FROM users WHERE email = ? OR username = ?");
    $stmt->bind_param("ss", $identifier, $identifier);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        header("Location: login.php?error=invalid");
        exit();
    }

    $user = $result->fetch_assoc();
    $stmt->close();

    // Verify password
    if (!password_verify($password, $user['password_hash'])) {
        header("Location: login.php?error=invalid");
        exit();
    }

    // Check verification flag
    if ((int)$user['is_verified'] !== 1) {
        header("Location: login.php?error=not_verified");
        exit();
    }

    // ✅ Create user session
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['username'] = $user['username'];
    $_SESSION['role'] = $user['role'];

    // ✅ Force PHP to save the session before redirecting
    session_write_close();

    // ✅ Redirect based on role
    switch ($user['role']) {
        case 'admin':
            header("Location: /admin/index.php");
            break;
        case 'artist':
            header("Location: /artist/index.php");
            break;
        case 'customer':
            header("Location: /customer/index.php");
            break;
        default:
            header("Location: index.php");
            break;
    }
    exit();
} else {
    header("Location: login.php?error=unauthorized");
    exit();
}
?>
