<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require '../config/db.php';
require '../config/function/function.php';

if (isset($_POST['submit'])) {
    $email = cleanInput($_POST['email']);
    $password = cleanInput($_POST['password']);

    $location = "./login";
    $message = "";
    $type = "";

    if (empty($email)) {
        $message = "Email is required.";
        $type = "error";
        exit();
    }

    if (empty($password)) {
        $message = "Password is required.";
        $type = "error";
        exit();
    }

    $email = $conn->real_escape_string($email);

    $query = "SELECT * FROM admin WHERE email='$email'";
    $result = $conn->query($query);

    if ($result) {
        if ($result->num_rows == 1) {
            $admin = $result->fetch_assoc();
            $db_password = $admin['password'];

            if (password_verify($password, $db_password)) {
                $_SESSION['adminId'] = $admin['id'];
                $_SESSION['admin'] = true;

                $message = "Welcome admin!";
                $type = "success";
                redirectWithMessage("./dashboard", $message, $type);
                exit();
            } else {
                $message = "Incorrect password.";
            }
        } else {
            $message = "User not found.";
        }
    } else {
        $message = "Database error: " . $conn->error;
    }

    redirectWithMessage($location, $message, $type);
    exit();
} else {
    $message = "Invalid request.";
    $type = "error";
    redirectWithMessage("./login", $message, $type);
    exit();
}