<?php
/**
 * Super Administrator Login Page
 * Location: public_html/admin/login_admin.php
 * Default Credentials: Username: "admin" / Password: "admin"
 */

require_once __DIR__ . '/../connections/connect.php';
if (file_exists(__DIR__ . '/../includes/functions.php')) {
    require_once __DIR__ . '/../includes/functions.php';
}

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Defensive helper fallback
if (!function_exists('is_admin_logged_in')) {
    function is_admin_logged_in() {
        return isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true && !empty($_SESSION['admin_user_id']);
    }
}
if (!function_exists('sanitize_input')) {
    function sanitize_input($data) {
        return htmlspecialchars(trim((string)$data), ENT_QUOTES, 'UTF-8');
    }
}

// If admin already logged in, redirect to admin dashboard
if (is_admin_logged_in()) {
    header("Location: dashboard_admin.php");
    exit;
}

$error = '';
$info = '';

if (isset($_GET['msg']) && $_GET['msg'] === 'logged_out') {
    $info = "You have been successfully logged out of the Super Admin Panel.";
}
if (isset($_GET['error'])) {
    $error = sanitize_input($_GET['error']);
}

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

    if (empty($username) || empty($password)) {
        $error = "Please enter both Super Admin username and password.";
    } else {
        try {
            // Check admin_users table for matching username
            $stmt = $pdo->prepare("SELECT * FROM admin_users WHERE username = :username AND is_active = 1 LIMIT 1");
            $stmt->execute(['username' => $username]);
            $admin = $stmt->fetch();

            $authenticated = false;

            if ($admin) {
                // Verify password against stored bcrypt hash, or check default seed admin/admin fallback
                if (password_verify($password, $admin['password_hash']) || ($username === 'admin' && $password === 'admin') || $admin['password_hash'] === $password) {
                    $authenticated = true;

                    // If the stored hash does not pass standard password_verify, auto-heal it in the database
                    if (!password_verify($password, $admin['password_hash'])) {
                        try {
                            $healHash = password_hash($password, PASSWORD_DEFAULT);
                            $healStmt = $pdo->prepare("UPDATE admin_users SET password_hash = :hash WHERE id = :id");
                            $healStmt->execute(['hash' => $healHash, 'id' => $admin['id']]);
                        } catch (Exception $e) {
                            // Non-blocking catch
                        }
                    }
                }
            } else if ($username === 'admin' && $password === 'admin') {
                // Fallback / Auto-seed initial admin if table is empty
                $adminId = 'adm_' . uniqid();
                $hashedPassword = password_hash('admin', PASSWORD_DEFAULT);
                
                $insertStmt = $pdo->prepare("INSERT INTO admin_users (id, username, password_hash, email, full_name, role, is_active) VALUES (:id, 'admin', :hash, 'admin@mibuildqc.local', 'System Super Administrator', 'SUPER_ADMIN', 1)");
                $insertStmt->execute([
                    'id' => $adminId,
                    'hash' => $hashedPassword
                ]);

                $admin = [
                    'id' => $adminId,
                    'username' => 'admin',
                    'email' => 'admin@mibuildqc.local',
                    'full_name' => 'System Super Administrator',
                    'role' => 'SUPER_ADMIN'
                ];
                $authenticated = true;
            }

            if ($authenticated) {
                // Regenerate session ID for security
                session_regenerate_id(true);

                $_SESSION['admin_logged_in'] = true;
                $_SESSION['admin_user_id'] = $admin['id'];
                $_SESSION['admin_username'] = $admin['username'];
                $_SESSION['admin_email'] = $admin['email'];
                $_SESSION['admin_full_name'] = $admin['full_name'];
                $_SESSION['admin_role'] = $admin['role'];

                // Update last login timestamp
                $updateStmt = $pdo->prepare("UPDATE admin_users SET last_login_at = NOW() WHERE id = :id");
                $updateStmt->execute(['id' => $admin['id']]);

                // Record audit log
                try {
                    $logStmt = $pdo->prepare("INSERT INTO audit_logs (id, account_id, user_id, action, details, ip_address) VALUES (:id, 'SYSTEM', :admin_id, 'ADMIN_LOGIN', 'Super Administrator logged into central admin console.', :ip)");
                    $logStmt->execute([
                        'id' => 'log_' . uniqid(),
                        'admin_id' => $admin['id'],
                        'ip' => $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1'
                    ]);
                } catch (Exception $e) {
                    // Non-blocking log catch
                }

                header("Location: dashboard_admin.php");
                exit;
            } else {
                $error = "Invalid administrator username or password. Default is 'admin' / 'admin'.";
            }
        } catch (PDOException $e) {
            $error = "Database error: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Super Admin Login - MiBuildqc Control Panel</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>body { font-family: 'Plus Jakarta Sans', sans-serif; }</style>
</head>
<body class="bg-slate-950 min-h-screen flex items-center justify-center p-4 text-slate-100">

    <div class="w-full max-w-md bg-slate-900 border border-slate-800 rounded-3xl p-8 shadow-2xl space-y-6">
        
        <!-- Header -->
        <div class="text-center space-y-2">
            <div class="w-14 h-14 rounded-2xl bg-indigo-600/20 border border-indigo-500/30 text-indigo-400 flex items-center justify-center mx-auto shadow-inner">
                <svg class="w-7 h-7" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"></path>
                </svg>
            </div>
            <h1 class="text-2xl font-extrabold tracking-tight text-white">Super Admin Portal</h1>
            <p class="text-xs text-slate-400">
                Centralized management for users, password resets, application metrics, and standard templates.
            </p>
        </div>

        <?php if (!empty($error)): ?>
            <div class="p-3.5 rounded-xl bg-rose-500/10 border border-rose-500/30 text-rose-300 text-xs flex items-center gap-2">
                <svg class="w-4 h-4 text-rose-400 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
                </svg>
                <span><?php echo htmlspecialchars($error); ?></span>
            </div>
        <?php endif; ?>

        <?php if (!empty($info)): ?>
            <div class="p-3.5 rounded-xl bg-indigo-500/10 border border-indigo-500/30 text-indigo-300 text-xs flex items-center gap-2">
                <svg class="w-4 h-4 text-indigo-400 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
                <span><?php echo htmlspecialchars($info); ?></span>
            </div>
        <?php endif; ?>

        <form action="login_admin.php" method="POST" class="space-y-4">
            <div>
                <label class="block text-xs font-semibold text-slate-300 mb-1.5">Admin Username</label>
                <div class="relative">
                    <input 
                        type="text" 
                        name="username" 
                        value="admin" 
                        required 
                        placeholder="admin"
                        class="w-full pl-10 pr-4 py-2.5 bg-slate-800 border border-slate-700 rounded-xl text-sm text-white focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                    >
                    <svg class="w-4 h-4 text-slate-400 absolute left-3.5 top-1/2 -translate-y-1/2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
                    </svg>
                </div>
            </div>

            <div>
                <label class="block text-xs font-semibold text-slate-300 mb-1.5">Admin Password</label>
                <div class="relative">
                    <input 
                        type="password" 
                        name="password" 
                        value="admin" 
                        required 
                        placeholder="admin"
                        class="w-full pl-10 pr-4 py-2.5 bg-slate-800 border border-slate-700 rounded-xl text-sm text-white focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                    >
                    <svg class="w-4 h-4 text-slate-400 absolute left-3.5 top-1/2 -translate-y-1/2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path>
                    </svg>
                </div>
            </div>

            <div class="p-3 bg-slate-800/60 rounded-xl border border-slate-700/60 text-xs text-slate-400 flex items-center justify-between">
                <span>Default Credentials:</span>
                <span class="font-mono text-indigo-300 font-bold bg-indigo-950/80 px-2 py-0.5 rounded border border-indigo-800">admin / admin</span>
            </div>

            <button 
                type="submit" 
                class="w-full py-3 px-4 bg-indigo-600 hover:bg-indigo-500 text-white rounded-xl text-xs font-bold uppercase tracking-wider transition-all shadow-lg shadow-indigo-600/30 flex items-center justify-center gap-2"
            >
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h7a3 3 0 013 3v1"></path>
                </svg>
                <span>Login to Admin Dashboard</span>
            </button>
        </form>

        <div class="pt-2 text-center">
            <a href="../login.php" class="text-xs text-slate-400 hover:text-slate-200 transition-colors inline-flex items-center gap-1.5">
                <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
                </svg>
                <span>Return to Standard Company Workspace</span>
            </a>
        </div>

    </div>

</body>
</html>