<?php
session_start();

require_once __DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'database.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php';

if (!isInstalled()) {
    redirect('/install/');
}

$auth = new Auth();
if ($auth->check()) {
    switch ($auth->userRole()) {
        case 'super_admin':
            redirect('/admin/');
            break;
        case 'restaurant_admin':
            redirect('/restaurant-admin/');
            break;
        case 'restaurant_manager':
            redirect('/restaurant-admin/');
            break;
        case 'kitchen_staff':
            redirect('/kitchen/');
            break;
        case 'waiter':
            redirect('/waiter/');
            break;
        case 'cashier':
            redirect('/cashier/');
            break;
        default:
            redirect('/login.php');
            break;
    }
}

$error = '';
$email = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $csrf = new CSRF();
    $token = $_POST[CSRF_TOKEN_NAME] ?? '';

    if (!$csrf->verify($token)) {
        $error = 'Invalid security token. Please try again.';
    } else {
        $email = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        $remember = isset($_POST['remember']);

        if (empty($email) || empty($password)) {
            $error = 'Please enter both email and password.';
        } else {
            $result = $auth->login($email, $password);

            if ($result['success']) {
                if ($remember) {
                    $params = session_get_cookie_params();
                    setcookie(
                        'tap2order_remember',
                        $result['user']['id'],
                        time() + (86400 * 30),
                        $params['path'],
                        $params['domain'],
                        $params['secure'],
                        $params['httponly']
                    );
                }

                $userRole = $result['user']['role_name'];
                switch ($userRole) {
                    case 'super_admin':
                        redirect('/admin/');
                        break;
                    case 'restaurant_admin':
                        redirect('/restaurant-admin/');
                        break;
                    case 'restaurant_manager':
                        redirect('/restaurant-admin/');
                        break;
                    case 'kitchen_staff':
                        redirect('/kitchen/');
                        break;
                    case 'waiter':
                        redirect('/waiter/');
                        break;
                    case 'cashier':
                        redirect('/cashier/');
                        break;
                    default:
                        redirect('/');
                        break;
                }
            } else {
                $error = $result['message'];
            }
        }
    }
}

$csrf = new CSRF();
$csrfToken = $csrf->generate();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - <?php echo sanitize(APP_NAME); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .login-container {
            width: 100%;
            max-width: 420px;
            padding: 15px;
        }
        .login-card {
            background: #fff;
            border-radius: 16px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
            padding: 40px;
            animation: slideUp 0.5s ease-out;
        }
        @keyframes slideUp {
            from { opacity: 0; transform: translateY(30px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .login-logo {
            text-align: center;
            margin-bottom: 30px;
        }
        .login-logo h1 {
            font-size: 28px;
            font-weight: 700;
            color: #333;
            margin-bottom: 5px;
        }
        .login-logo p {
            color: #888;
            font-size: 14px;
        }
        .login-logo .icon-circle {
            width: 70px;
            height: 70px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 15px;
        }
        .login-logo .icon-circle i {
            font-size: 32px;
            color: #fff;
        }
        .form-floating { margin-bottom: 16px; }
        .form-floating .form-control {
            border-radius: 10px;
            border: 2px solid #e9ecef;
            padding: 16px 14px;
            height: 52px;
            transition: border-color 0.3s;
        }
        .form-floating .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.15);
        }
        .form-floating label { padding: 16px 14px; }
        .btn-login {
            width: 100%;
            height: 50px;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            color: #fff;
            transition: transform 0.2s, box-shadow 0.2s;
        }
        .btn-login:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
            color: #fff;
        }
        .btn-login:active { transform: translateY(0); }
        .form-check { margin: 16px 0; }
        .form-check-input:checked {
            background-color: #667eea;
            border-color: #667eea;
        }
        .form-check-label { font-size: 14px; color: #666; }
        .forgot-link {
            text-align: right;
            margin-top: -8px;
            margin-bottom: 16px;
        }
        .forgot-link a {
            font-size: 13px;
            color: #667eea;
            text-decoration: none;
        }
        .forgot-link a:hover { text-decoration: underline; }
        .alert { border-radius: 10px; font-size: 14px; }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-card">
            <div class="login-logo">
                <div class="icon-circle">
                    <i class="bi bi-qr-code-scan"></i>
                </div>
                <h1><?php echo sanitize(APP_NAME); ?></h1>
                <p>Sign in to your account</p>
            </div>

            <?php if (!empty($error)): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="bi bi-exclamation-triangle-fill me-2"></i>
                    <?php echo sanitize($error); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <form method="POST" action="" id="loginForm">
                <?php echo $csrf->field(); ?>

                <div class="form-floating">
                    <input type="email" class="form-control" id="email" name="email"
                           placeholder="Email address" required autofocus
                           value="<?php echo sanitize($email); ?>">
                    <label for="email"><i class="bi bi-envelope me-2"></i>Email address</label>
                </div>

                <div class="form-floating">
                    <input type="password" class="form-control" id="password" name="password"
                           placeholder="Password" required>
                    <label for="password"><i class="bi bi-lock me-2"></i>Password</label>
                </div>

                <div class="forgot-link">
                    <a href="forgot-password.php">Forgot password?</a>
                </div>

                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="remember" name="remember">
                    <label class="form-check-label" for="remember">Remember me</label>
                </div>

                <button type="submit" class="btn btn-login">
                    <i class="bi bi-box-arrow-in-right me-2"></i>Sign In
                </button>
            </form>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.getElementById('loginForm').addEventListener('submit', function() {
            var btn = this.querySelector('button[type="submit"]');
            btn.disabled = true;
            btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status"></span>Signing in...';
        });
    </script>
</body>
</html>
