<?php
/**
 * Pure Chemical Admin Panel
 * File: /admin/login.php
 *
 * Premium Modern Login
 */

declare(strict_types=1);

session_start();

$pdo = null;

require_once __DIR__ . '/includes/db.php';


/* =========================================================
   ALREADY LOGGED IN
   ========================================================= */

if (!empty($_SESSION['admin_id'])) {
    header('Location: dashboard.php');
    exit;
}


/* =========================================================
   SECURITY TOKEN
   ========================================================= */

if (empty($_SESSION['login_csrf'])) {
    $_SESSION['login_csrf'] = bin2hex(random_bytes(32));
}


/* =========================================================
   LOGIN PROCESS
   ========================================================= */

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $csrf = $_POST['csrf_token'] ?? '';

    if (
        !hash_equals(
            $_SESSION['login_csrf'],
            $csrf
        )
    ) {
        $error = 'Invalid security request. Please refresh the page and try again.';
    } else {

        $email = trim((string)($_POST['email'] ?? ''));
        $password = (string)($_POST['password'] ?? '');
        $remember = isset($_POST['remember']);

        if ($email === '' || $password === '') {

            $error = 'Please enter your email and password.';

        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

            $error = 'Please enter a valid email address.';

        } else {

            try {

                /*
                 * Plain-text password comparison is used as requested.
                 * Supports either an `admins.password` column or the existing
                 * `admins.password_hash` column name, but the stored value
                 * must be the plain password in either case.
                 */

                if (!$pdo instanceof PDO) {
                    error_log('Admin login failed: database connection is unavailable.');
                    $error = 'Database connection error. Please try again later.';
                } else {
                    $columnStmt = $pdo->query("SHOW COLUMNS FROM admins");
                    $adminColumns = $columnStmt->fetchAll(PDO::FETCH_COLUMN);

                    if (in_array('password', $adminColumns, true)) {
                        $passwordColumn = 'password';
                    } elseif (in_array('password_hash', $adminColumns, true)) {
                        // Legacy column name; values are compared as plain text.
                        $passwordColumn = 'password_hash';
                    } else {
                        throw new PDOException('No password column found in admins table.');
                    }

                    $stmt = $pdo->prepare("
                        SELECT
                            id,
                            name,
                            email,
                            `{$passwordColumn}` AS login_password,
                            status
                        FROM admins
                        WHERE email = ?
                        LIMIT 1
                    ");

                    $stmt->execute([$email]);
                    $admin = $stmt->fetch(PDO::FETCH_ASSOC);

                    if (
                        !$admin ||
                        !hash_equals((string)$admin['login_password'], $password)
                    ) {
                        $error = 'Invalid email or password.';
                    } elseif ((string)$admin['status'] !== '1') {
                        $error = 'Your administrator account is inactive.';
                    } else {
                        /*
                         * Prevent session fixation.
                         */
                        session_regenerate_id(true);

                        $_SESSION['admin_id'] = (int)$admin['id'];
                        $_SESSION['admin_name'] = $admin['name'];
                        $_SESSION['admin_email'] = $admin['email'];
                        $_SESSION['admin_logged_in'] = true;

                        /*
                         * Optional remember flag.
                         *
                         * We keep the session-based login here.
                         * Long-lived authentication can be added later
                         * using a secure selector/token system.
                         */
                        $_SESSION['remember_admin'] = $remember;

                        /*
                         * Rotate CSRF token after successful login.
                         */
                        $_SESSION['login_csrf'] =
                            bin2hex(random_bytes(32));

                        header('Location: dashboard.php');
                        exit;
                    }
                }
            } catch (PDOException $e) {

                error_log(
                    'Admin Login Error: ' . $e->getMessage()
                );

                $error =
                    'Something went wrong while signing you in. Please try again.';
            }
        }
    }
}


/* =========================================================
   LOGOUT / SESSION MESSAGE
   ========================================================= */

if (
    isset($_GET['logout']) &&
    $_GET['logout'] === '1'
) {
    $success = 'You have been signed out successfully.';
}


/* =========================================================
   OLD INPUT
   ========================================================= */

$oldEmail = htmlspecialchars(
    $_POST['email'] ?? '',
    ENT_QUOTES,
    'UTF-8'
);

?>
<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <meta
        name="robots"
        content="noindex,nofollow"
    >

    <title>Admin Login | Pure Chemical</title>

    <style>

        /* =====================================================
           RESET
           ===================================================== */

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        html,
        body {
            min-height: 100%;
        }

        body {
            font-family:
                Inter,
                ui-sans-serif,
                system-ui,
                -apple-system,
                BlinkMacSystemFont,
                "Segoe UI",
                sans-serif;

            background:
                radial-gradient(
                    circle at 15% 20%,
                    rgba(30, 115, 255, 0.18),
                    transparent 30%
                ),
                radial-gradient(
                    circle at 85% 80%,
                    rgba(0, 194, 168, 0.15),
                    transparent 30%
                ),
                #07111f;

            color: #fff;

            display: flex;
            align-items: center;
            justify-content: center;

            min-height: 100vh;

            overflow-x: hidden;
        }


        /* =====================================================
           BACKGROUND
           ===================================================== */

        .background {
            position: fixed;
            inset: 0;
            pointer-events: none;
            overflow: hidden;
            z-index: 0;
        }

        .orb {
            position: absolute;
            border-radius: 50%;
            filter: blur(2px);
            opacity: .45;
        }

        .orb-one {
            width: 420px;
            height: 420px;
            background: rgba(32, 122, 255, .12);
            top: -180px;
            left: -130px;
        }

        .orb-two {
            width: 360px;
            height: 360px;
            background: rgba(0, 210, 180, .10);
            bottom: -160px;
            right: -100px;
        }

        .grid {
            position: absolute;
            inset: 0;

            background-image:
                linear-gradient(
                    rgba(255,255,255,.025) 1px,
                    transparent 1px
                ),
                linear-gradient(
                    90deg,
                    rgba(255,255,255,.025) 1px,
                    transparent 1px
                );

            background-size: 42px 42px;

            mask-image:
                linear-gradient(
                    to bottom,
                    black,
                    transparent
                );
        }


        /* =====================================================
           LAYOUT
           ===================================================== */

        .login-wrapper {
            width: min(1080px, calc(100% - 32px));

            display: grid;
            grid-template-columns: 1fr 1fr;

            position: relative;
            z-index: 1;

            border: 1px solid rgba(255,255,255,.09);

            border-radius: 28px;

            overflow: hidden;

            background:
                rgba(9, 20, 34, .78);

            backdrop-filter: blur(24px);
            -webkit-backdrop-filter: blur(24px);

            box-shadow:
                0 40px 100px rgba(0,0,0,.45),
                inset 0 1px 0 rgba(255,255,255,.04);
        }


        /* =====================================================
           BRAND PANEL
           ===================================================== */

        .brand-panel {
            position: relative;

            padding: 58px;

            min-height: 650px;

            display: flex;
            flex-direction: column;
            justify-content: space-between;

            background:
                linear-gradient(
                    145deg,
                    rgba(20, 61, 105, .58),
                    rgba(7, 18, 32, .35)
                );

            border-right:
                1px solid rgba(255,255,255,.07);
        }

        .brand-top {
            display: flex;
            align-items: center;
            gap: 14px;
        }

        .brand-mark {
            width: 48px;
            height: 48px;

            display: flex;
            align-items: center;
            justify-content: center;

            border-radius: 14px;

            background:
                linear-gradient(
                    135deg,
                    #ffffff,
                    #dceeff
                );

            color: #0b4d86;

            font-size: 20px;
            font-weight: 800;

            box-shadow:
                0 10px 30px rgba(0,0,0,.18);
        }

        .brand-name {
            font-size: 19px;
            font-weight: 750;
            letter-spacing: -.3px;
        }

        .brand-label {
            margin-top: 3px;

            color: rgba(255,255,255,.52);

            font-size: 11px;
            letter-spacing: 1.5px;
            text-transform: uppercase;
        }

        .brand-content {
            max-width: 450px;
        }

        .eyebrow {
            display: inline-flex;

            align-items: center;
            gap: 8px;

            padding: 7px 11px;

            border-radius: 999px;

            background: rgba(255,255,255,.055);

            border:
                1px solid rgba(255,255,255,.08);

            color: rgba(255,255,255,.68);

            font-size: 11px;
            font-weight: 650;

            letter-spacing: 1.2px;
            text-transform: uppercase;
        }

        .eyebrow-dot {
            width: 6px;
            height: 6px;

            border-radius: 50%;

            background: #46d7b2;

            box-shadow:
                0 0 12px rgba(70,215,178,.8);
        }

        .brand-content h1 {
            margin-top: 22px;

            font-size: clamp(36px, 4vw, 58px);

            line-height: 1.02;

            letter-spacing: -2.8px;

            font-weight: 760;
        }

        .brand-content h1 span {
            background:
                linear-gradient(
                    100deg,
                    #ffffff,
                    #8bd7ff
                );

            -webkit-background-clip: text;
            background-clip: text;

            color: transparent;
        }

        .brand-content p {
            margin-top: 20px;

            max-width: 410px;

            color: rgba(255,255,255,.57);

            font-size: 14px;

            line-height: 1.75;
        }

        .brand-footer {
            color: rgba(255,255,255,.36);

            font-size: 12px;
        }


        /* =====================================================
           FORM PANEL
           ===================================================== */

        .form-panel {
            padding: 58px;

            display: flex;
            align-items: center;

            background:
                rgba(5, 14, 25, .44);
        }

        .form-container {
            width: 100%;
            max-width: 410px;
            margin: auto;
        }

        .form-header h2 {
            font-size: 30px;

            letter-spacing: -1px;

            font-weight: 740;
        }

        .form-header p {
            margin-top: 9px;

            color: rgba(255,255,255,.48);

            font-size: 13px;

            line-height: 1.6;
        }


        /* =====================================================
           ALERTS
           ===================================================== */

        .alert {
            margin-top: 24px;

            padding: 13px 14px;

            border-radius: 13px;

            font-size: 12px;

            line-height: 1.5;

            border: 1px solid;
        }

        .alert-error {
            color: #ffd6d6;

            background: rgba(190, 40, 55, .12);

            border-color:
                rgba(255, 92, 110, .22);
        }

        .alert-success {
            color: #c8ffe9;

            background: rgba(22, 170, 125, .10);

            border-color:
                rgba(70, 215, 178, .22);
        }


        /* =====================================================
           FORM
           ===================================================== */

        form {
            margin-top: 30px;
        }

        .field {
            margin-bottom: 19px;
        }

        .field-label {
            display: block;

            margin-bottom: 8px;

            color: rgba(255,255,255,.72);

            font-size: 12px;

            font-weight: 650;
        }

        .input-wrap {
            position: relative;
        }

        .input-icon {
            position: absolute;

            left: 15px;
            top: 50%;

            transform: translateY(-50%);

            color: rgba(255,255,255,.35);

            pointer-events: none;

            font-size: 15px;
        }

        .input {
            width: 100%;

            height: 50px;

            padding:
                0 45px 0 43px;

            border-radius: 13px;

            border:
                1px solid rgba(255,255,255,.10);

            outline: none;

            background:
                rgba(255,255,255,.045);

            color: #fff;

            font-size: 13px;

            transition:
                border-color .2s ease,
                background .2s ease,
                box-shadow .2s ease;
        }

        .input::placeholder {
            color: rgba(255,255,255,.28);
        }

        .input:focus {
            border-color:
                rgba(93, 180, 255, .55);

            background:
                rgba(255,255,255,.065);

            box-shadow:
                0 0 0 4px
                rgba(40, 143, 255, .09);
        }

        .password-toggle {
            position: absolute;

            right: 13px;
            top: 50%;

            transform: translateY(-50%);

            border: 0;
            background: transparent;

            color: rgba(255,255,255,.36);

            cursor: pointer;

            font-size: 12px;

            padding: 6px;
        }

        .password-toggle:hover {
            color: rgba(255,255,255,.75);
        }


        /* =====================================================
           OPTIONS
           ===================================================== */

        .form-options {
            display: flex;

            align-items: center;
            justify-content: space-between;

            margin: 4px 0 24px;
        }

        .remember {
            display: flex;
            align-items: center;
            gap: 8px;

            color: rgba(255,255,255,.46);

            font-size: 12px;

            cursor: pointer;
        }

        .remember input {
            width: 14px;
            height: 14px;

            accent-color: #389bff;
        }


        /* =====================================================
           BUTTON
           ===================================================== */

        .login-button {
            width: 100%;

            height: 52px;

            border: 0;

            border-radius: 14px;

            background:
                linear-gradient(
                    135deg,
                    #2488ff,
                    #25a9e9
                );

            color: #fff;

            font-size: 13px;

            font-weight: 720;

            letter-spacing: .1px;

            cursor: pointer;

            box-shadow:
                0 14px 30px
                rgba(25, 130, 240, .20);

            transition:
                transform .2s ease,
                box-shadow .2s ease,
                opacity .2s ease;
        }

        .login-button:hover {
            transform: translateY(-1px);

            box-shadow:
                0 18px 36px
                rgba(25, 130, 240, .30);
        }

        .login-button:active {
            transform: translateY(0);
        }

        .login-button.loading {
            pointer-events: none;
            opacity: .72;
        }


        /* =====================================================
           SECURITY NOTE
           ===================================================== */

        .security-note {
            margin-top: 25px;

            display: flex;

            justify-content: center;
            align-items: center;

            gap: 7px;

            color: rgba(255,255,255,.29);

            font-size: 10px;

            text-align: center;
        }

        .security-icon {
            font-size: 11px;
        }


        /* =====================================================
           RESPONSIVE
           ===================================================== */

        @media (max-width: 820px) {

            .login-wrapper {
                grid-template-columns: 1fr;

                max-width: 520px;
            }

            .brand-panel {
                min-height: auto;

                padding: 34px;

                gap: 70px;

                border-right: 0;

                border-bottom:
                    1px solid rgba(255,255,255,.07);
            }

            .brand-content h1 {
                font-size: 42px;
            }

            .brand-footer {
                display: none;
            }

            .form-panel {
                padding: 36px 34px 42px;
            }
        }


        @media (max-width: 480px) {

            body {
                padding: 15px;
            }

            .login-wrapper {
                width: 100%;

                border-radius: 22px;
            }

            .brand-panel {
                padding: 28px;
            }

            .form-panel {
                padding: 30px 24px 34px;
            }

            .brand-content h1 {
                font-size: 35px;

                letter-spacing: -1.8px;
            }

            .brand-content p {
                font-size: 13px;
            }

            .form-header h2 {
                font-size: 26px;
            }
        }

    </style>

</head>

<body>

<div class="background">
    <div class="orb orb-one"></div>
    <div class="orb orb-two"></div>
    <div class="grid"></div>
</div>


<div class="login-wrapper">


    <!-- =====================================================
         BRAND SIDE
         ===================================================== -->

    <section class="brand-panel">

        <div class="brand-top">

            <div class="brand-mark">
                PC
            </div>

            <div>
                <div class="brand-name">
                    Pure Chemical
                </div>

                <div class="brand-label">
                    Administration
                </div>
            </div>

        </div>


        <div class="brand-content">

            <div class="eyebrow">
                <span class="eyebrow-dot"></span>
                Secure Admin Portal
            </div>

            <h1>
                Manage your
                <span>chemical business.</span>
            </h1>

            <p>
                Manage products, industries, services, brands,
                pages, media, enquiries and every other part of
                your Pure Chemical website from one secure
                administration panel.
            </p>

        </div>


        <div class="brand-footer">
            © <?= date('Y'); ?> Pure Chemical. All rights reserved.
        </div>

    </section>



    <!-- =====================================================
         LOGIN SIDE
         ===================================================== -->

    <section class="form-panel">

        <div class="form-container">

            <div class="form-header">

                <h2>
                    Welcome back
                </h2>

                <p>
                    Sign in to continue to your administration
                    dashboard.
                </p>

            </div>


            <?php if ($error !== ''): ?>

                <div class="alert alert-error">
                    <?= htmlspecialchars(
                        $error,
                        ENT_QUOTES,
                        'UTF-8'
                    ); ?>
                </div>

            <?php endif; ?>


            <?php if ($success !== ''): ?>

                <div class="alert alert-success">
                    <?= htmlspecialchars(
                        $success,
                        ENT_QUOTES,
                        'UTF-8'
                    ); ?>
                </div>

            <?php endif; ?>


            <form
                method="POST"
                action=""
                autocomplete="on"
                id="loginForm"
            >

                <input
                    type="hidden"
                    name="csrf_token"
                    value="<?= htmlspecialchars(
                        $_SESSION['login_csrf'],
                        ENT_QUOTES,
                        'UTF-8'
                    ); ?>"
                >


                <!-- EMAIL -->

                <div class="field">

                    <label
                        class="field-label"
                        for="email"
                    >
                        Email address
                    </label>

                    <div class="input-wrap">

                        <span class="input-icon">
                            ✉
                        </span>

                        <input
                            class="input"
                            type="email"
                            id="email"
                            name="email"
                            value="<?= $oldEmail; ?>"
                            placeholder="admin@example.com"
                            autocomplete="username"
                            required
                            autofocus
                        >

                    </div>

                </div>


                <!-- PASSWORD -->

                <div class="field">

                    <label
                        class="field-label"
                        for="password"
                    >
                        Password
                    </label>

                    <div class="input-wrap">

                        <span class="input-icon">
                            •••
                        </span>

                        <input
                            class="input"
                            type="password"
                            id="password"
                            name="password"
                            placeholder="Enter your password"
                            autocomplete="current-password"
                            required
                        >

                        <button
                            type="button"
                            class="password-toggle"
                            id="passwordToggle"
                            aria-label="Show password"
                        >
                            Show
                        </button>

                    </div>

                </div>


                <!-- OPTIONS -->

                <div class="form-options">

                    <label class="remember">

                        <input
                            type="checkbox"
                            name="remember"
                            value="1"
                        >

                        Remember me

                    </label>

                </div>


                <!-- LOGIN -->

                <button
                    type="submit"
                    class="login-button"
                    id="loginButton"
                >
                    Sign in to Admin
                </button>

            </form>


            <div class="security-note">

                <span class="security-icon">●</span>

                Protected administrator access

            </div>

        </div>

    </section>

</div>


<script>

    /* =========================================================
       PASSWORD VISIBILITY
       ========================================================= */

    const passwordInput =
        document.getElementById('password');

    const passwordToggle =
        document.getElementById('passwordToggle');

    passwordToggle.addEventListener('click', function () {

        const isPassword =
            passwordInput.type === 'password';

        passwordInput.type =
            isPassword ? 'text' : 'password';

        this.textContent =
            isPassword ? 'Hide' : 'Show';

        this.setAttribute(
            'aria-label',
            isPassword
                ? 'Hide password'
                : 'Show password'
        );
    });


    /* =========================================================
       LOGIN BUTTON STATE
       ========================================================= */

    const loginForm =
        document.getElementById('loginForm');

    const loginButton =
        document.getElementById('loginButton');

    loginForm.addEventListener('submit', function () {

        loginButton.classList.add('loading');

        loginButton.textContent =
            'Signing in…';

    });

</script>

</body>
</html>
