<?php
session_start();
require_once '../src/Database.php';

$conn = Database::getInstance();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email    = trim($_POST['email']);
    $password = trim($_POST['password']);

    $stmt = $conn->prepare("SELECT id, name, folder_id, project_id, bitrix24_user_id, email, password FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows === 1) {
        $stmt->bind_result($id, $name, $folderId, $projectId, $bitrix24UserId, $dbEmail, $hashedPassword);
        $stmt->fetch();

        if (password_verify($password, $hashedPassword)) {
            $_SESSION['user_id']        = $id;
            $_SESSION['username']       = $name;
            $_SESSION['folder_id']      = $folderId;
            $_SESSION['project_id']     = $projectId;
            $_SESSION['bitrix_user_id'] = $bitrix24UserId;
            $_SESSION['user_email']     = $dbEmail;

            header("Location: https://integrations.notamedia.co.in/helpdesk-core-php/ticket-user/index.php");
            exit;
        } else {
            echo "❌ Incorrect password.";
        }
    } else {
        echo "❌ User not found.";
    }

    $stmt->close();
    $conn->close();
}
?>
