<?php
session_start();
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");

if (isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit();
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    include 'layouts/dbconn.php';

    $username = trim($_POST['username']);
    $password = $_POST['password'];

    if (empty($username) || empty($password)) {
        $error_message = "Username and password are required.";
    } else {
        $ip_address = $_SERVER['REMOTE_ADDR'];
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';

        try {
            $sql = "SELECT u.id, u.full_name, u.username, u.email, u.phone,
                           u.password_hash, u.status, u.business_id, u.role_id,
                           r.role_name, b.business_name
                    FROM   users u
                    JOIN   roles r ON r.id = u.role_id
                    JOIN   businesses b ON b.id = u.business_id
                    WHERE  (u.username = ? OR u.email = ?)
                      AND  u.status   = 'active'
                      AND  b.status   = 'active'
                    LIMIT  1";

            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ss", $username, $username);
            $stmt->execute();
            $result = $stmt->get_result();

            if ($result->num_rows > 0) {
                $user = $result->fetch_assoc();

                if (password_verify($password, $user['password_hash'])) {
                    /* ── Fetch assigned locations ─────────────────────────── */
                    $locations = [];
                    $loc_sql = "SELECT l.id, l.location_name, l.till_number
                                FROM   user_locations ul
                                JOIN   locations l ON l.id = ul.location_id
                                WHERE  ul.user_id = ? AND l.is_active = 1
                                ORDER  BY l.location_name";
                    $loc_stmt = $conn->prepare($loc_sql);
                    $loc_stmt->bind_param("i", $user['id']);
                    $loc_stmt->execute();
                    $loc_res = $loc_stmt->get_result();
                    while ($row = $loc_res->fetch_assoc()) {
                        $locations[] = $row;
                    }
                    $loc_stmt->close();

                    /* ── Set session ──────────────────────────────────────── */
                    $_SESSION['user_id']            = $user['id'];
                    $_SESSION['username']           = $user['username'];
                    $_SESSION['full_name']          = $user['full_name'];
                    $_SESSION['phone']              = $user['phone'];
                    $_SESSION['role_id']            = $user['role_id'];
                    $_SESSION['role_name']          = $user['role_name'];
                    $_SESSION['business_id']        = $user['business_id'];
                    $_SESSION['business_name']      = $user['business_name'];
                    $_SESSION['locations']          = $locations;
                    $_SESSION['primary_location_id'] = !empty($locations) ? $locations[0]['id'] : null;
                    $_SESSION['primary_location_name'] = !empty($locations) ? $locations[0]['location_name'] : null;
                    $_SESSION['login_time']         = time();
                    $_SESSION['session_token']      = bin2hex(random_bytes(32));

                    /* ── Audit log ────────────────────────────────────────── */
                    $log_sql = "INSERT INTO audit_logs
                                    (business_id, user_id, action, table_name, ip_address, user_agent, new_values)
                                VALUES (?, ?, 'LOGIN', 'users', ?, ?, ?)";
                    $log_stmt = $conn->prepare($log_sql);
                    $log_data = json_encode([
                        'login_time' => date('Y-m-d H:i:s'),
                        'role'       => $user['role_name'],
                        'locations'  => array_column($locations, 'location_name'),
                        'ip'         => $ip_address
                    ]);
                    $log_stmt->bind_param("iisss",
                        $user['business_id'], $user['id'],
                        $ip_address, $user_agent, $log_data
                    );
                    $log_stmt->execute();
                    $log_stmt->close();

                    header("Location: index.php");
                    exit();

                } else {
                    $error_message = "Invalid username or password.";
                }
            } else {
                $error_message = "Invalid username or password.";
            }

            $stmt->close();
        } catch (Exception $e) {
            error_log("Login error: " . $e->getMessage());
            $error_message = "A system error occurred. Please try again.";
        }

        $conn->close();
    }
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php',
        ['title' => 'Sign In — Christmond M-Pesa Agent System']); ?>
    <?php include 'layouts/head-css.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <style>
        :root {
            --mpesa-green:       #00a651;
            --mpesa-green-dark:  #007a3d;
            --mpesa-green-light: #34c470;
            --mpesa-red:         #e2231a;
            --light-green:       #e8f8ef;
            --very-light-green:  #f2fbf6;
            --text-dark:         #1a2e1a;
            --text-muted:        #6c757d;
            --border-color:      #dee2e6;
        }

        body { background: linear-gradient(135deg, var(--very-light-green) 0%, var(--light-green) 100%); min-height: 100vh; }

        .auth-page-wrapper { background: linear-gradient(135deg, var(--very-light-green) 0%, var(--light-green) 100%); }

        .card {
            border: none;
            box-shadow: 0 12px 40px rgba(0,166,81,.12);
            border-radius: 18px;
            overflow: hidden;
        }
        .card::before {
            content: '';
            position: absolute; top: 0; left: 0; right: 0; height: 4px;
            background: linear-gradient(90deg, var(--mpesa-green) 0%, var(--mpesa-green-light) 100%);
            z-index: 1;
        }

        /* Left panel */
        .brand-panel {
            background: linear-gradient(160deg, var(--mpesa-green-dark) 0%, var(--mpesa-green) 60%, var(--mpesa-green-light) 100%);
            color: #fff;
        }
        .brand-panel h4, .brand-panel p { color: #fff !important; }
        .stat-badge {
            background: rgba(255,255,255,.15);
            border: 1px solid rgba(255,255,255,.25);
            border-radius: 12px;
            padding: 14px 18px;
            margin-bottom: 12px;
            display: flex;
            align-items: center;
            gap: 14px;
        }
        .stat-badge i { font-size: 1.6rem; opacity: .9; }
        .stat-badge small { display: block; opacity: .8; font-size: .72rem; letter-spacing: .04em; }
        .stat-badge strong { font-size: .95rem; }

        /* Form */
        .form-control {
            border: 2px solid var(--border-color);
            border-radius: 8px;
            padding: 11px 15px;
            font-size: .9rem;
            transition: all .25s;
        }
        .form-control:focus { border-color: var(--mpesa-green); box-shadow: 0 0 0 .2rem rgba(0,166,81,.2); }

        .input-group-text {
            background: var(--light-green);
            border: 2px solid var(--border-color);
            border-right: none;
            color: var(--mpesa-green);
        }

        .btn-mpesa {
            background: linear-gradient(135deg, var(--mpesa-green) 0%, var(--mpesa-green-light) 100%);
            border: none;
            border-radius: 8px;
            padding: 12px 24px;
            font-weight: 600;
            color: #fff;
            transition: all .3s;
        }
        .btn-mpesa:hover {
            background: linear-gradient(135deg, var(--mpesa-green-dark) 0%, var(--mpesa-green) 100%);
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0,166,81,.3);
            color: #fff;
        }
        .btn-mpesa:disabled { opacity: .75; transform: none; }

        .btn-outline-secondary:hover { background: var(--light-green); border-color: var(--mpesa-green); color: var(--mpesa-green); }

        .alert-danger { background: #fff5f5; border-color: #fed7d7; color: #c0392b; border-left: 4px solid var(--mpesa-red); }

        a { color: var(--mpesa-green); }
        a:hover { color: var(--mpesa-green-dark); }

        .text-mpesa { color: var(--mpesa-green) !important; }

        .roles-box { background: var(--very-light-green); border: 1px solid rgba(0,166,81,.15); border-radius: 10px; padding: 14px 18px; }

        @media (max-width: 768px) { .card { margin: 15px; } }
    </style>
</head>

<body>
<div class="auth-page-wrapper py-5 d-flex justify-content-center align-items-center min-vh-100">
    <div class="auth-page-content overflow-hidden pt-lg-5">
        <div class="container">
            <div class="row">
                <div class="col-lg-12">
                    <div class="card overflow-hidden border-0 shadow-lg position-relative">
                        <div class="row g-0">

                            <!-- ── Left brand panel ── -->
                            <div class="col-lg-5">
                                <div class="brand-panel p-lg-5 p-4 h-100 d-flex flex-column justify-content-center">

                                    <div class="text-center mb-4">
                                        <img src="assets/images/logo-christmond.png"
                                             onerror="this.style.display='none'"
                                             alt="Christmond" height="70" class="mb-3">

                                        <div class="mb-2" style="font-size:2rem; font-weight:800; letter-spacing:-.5px;">
                                            <span style="color:#fff;">M</span><span style="color:#fff;opacity:.7;">-PESA</span>
                                        </div>
                                        <h4 class="mb-1">Christmond Investment Ltd</h4>
                                        <p style="opacity:.8; font-size:.85rem;">Agent Management System</p>
                                    </div>

                                    <div class="mt-2">
                                        <div class="stat-badge">
                                            <i class="ri-store-2-line"></i>
                                            <div>
                                                <strong>Multi-Branch Floats</strong>
                                                <small>M-Pesa · Equity · KCB · Co-op · NCBA · ABSA · DIM</small>
                                            </div>
                                        </div>
                                        <div class="stat-badge">
                                            <i class="ri-file-list-3-line"></i>
                                            <div>
                                                <strong>Daily Session Tracking</strong>
                                                <small>Open · Transactions · Close · Reconcile</small>
                                            </div>
                                        </div>
                                        <div class="stat-badge">
                                            <i class="ri-shield-check-line"></i>
                                            <div>
                                                <strong>Short &amp; Excess Detection</strong>
                                                <small>Automated end-of-day reconciliation</small>
                                            </div>
                                        </div>
                                        <div class="stat-badge">
                                            <i class="ri-bar-chart-2-line"></i>
                                            <div>
                                                <strong>Commission Reports</strong>
                                                <small>Real-time earnings per branch &amp; agent</small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- ── Right login form ── -->
                            <div class="col-lg-7">
                                <div class="p-lg-5 p-4">

                                    <div class="text-center mb-4">
                                        <h5 class="text-mpesa mb-1">Welcome Back</h5>
                                        <p class="text-muted small">Sign in to manage your M-Pesa agent operations</p>
                                    </div>

                                    <?php if (isset($error_message)): ?>
                                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                            <i class="ri-error-warning-line me-2"></i>
                                            <?= htmlspecialchars($error_message) ?>
                                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                        </div>
                                    <?php endif; ?>

                                    <form id="login-form" method="POST" novalidate>

                                        <div class="mb-3">
                                            <label for="username" class="form-label fw-semibold">Username or Email</label>
                                            <div class="input-group">
                                                <span class="input-group-text"><i class="ri-user-line"></i></span>
                                                <input type="text" class="form-control" id="username" name="username"
                                                       placeholder="Enter username or email"
                                                       value="<?= isset($_POST['username']) ? htmlspecialchars($_POST['username']) : '' ?>"
                                                       required autocomplete="username">
                                            </div>
                                        </div>

                                        <div class="mb-3">
                                            <div class="d-flex justify-content-between mb-1">
                                                <label class="form-label fw-semibold mb-0" for="password">Password</label>
                                                <a href="forgot_password.php" class="text-muted small">
                                                    <i class="ri-lock-2-line me-1"></i>Forgot password?
                                                </a>
                                            </div>
                                            <div class="input-group">
                                                <span class="input-group-text"><i class="ri-lock-line"></i></span>
                                                <input type="password" class="form-control" id="password"
                                                       name="password" placeholder="Enter password"
                                                       required autocomplete="current-password">
                                                <button class="btn btn-outline-secondary" type="button" id="toggle-pw">
                                                    <i class="ri-eye-line"></i>
                                                </button>
                                            </div>
                                        </div>

                                        <div class="form-check mb-4">
                                            <input class="form-check-input" type="checkbox" id="remember">
                                            <label class="form-check-label text-muted" for="remember">
                                                Keep me signed in
                                            </label>
                                        </div>

                                        <button type="submit" class="btn btn-mpesa w-100" id="login-btn">
                                            <i class="ri-login-box-line me-2"></i>Sign In
                                        </button>

                                        <!-- Access levels -->
                                        <div class="roles-box mt-4">
                                            <h6 class="text-mpesa mb-2 small fw-bold">
                                                <i class="ri-group-line me-1"></i>Access Levels
                                            </h6>
                                            <div class="row g-2">
                                                <div class="col-6">
                                                    <small class="text-muted">
                                                        <i class="ri-shield-star-line text-mpesa me-1"></i>
                                                        <strong>Super Admin</strong> — Full access
                                                    </small>
                                                </div>
                                                <div class="col-6">
                                                    <small class="text-muted">
                                                        <i class="ri-user-settings-line text-mpesa me-1"></i>
                                                        <strong>Manager</strong> — Branch oversight
                                                    </small>
                                                </div>
                                                <div class="col-6">
                                                    <small class="text-muted">
                                                        <i class="ri-user-line text-mpesa me-1"></i>
                                                        <strong>Agent</strong> — Daily teller
                                                    </small>
                                                </div>
                                                <div class="col-6">
                                                    <small class="text-muted">
                                                        <i class="ri-search-eye-line text-mpesa me-1"></i>
                                                        <strong>Auditor</strong> — Read-only
                                                    </small>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Support -->
                                        <div class="text-center mt-3">
                                            <small class="text-muted">
                                                Need help?
                                                <a href="mailto:christmondinvestmentlimited@ymail.com">
                                                    christmondinvestmentlimited@ymail.com
                                                </a>
                                            </small>
                                        </div>

                                    </form>
                                </div>
                            </div>
                            <!-- end right col -->

                        </div>
                    </div>
                    <!-- end card -->

                    <div class="text-center mt-3">
                        <p class="mb-0 text-muted small">
                            &copy; <?= date('Y') ?>
                            <span class="fw-semibold" style="color:var(--mpesa-green);">
                                Christmond Investment Limited
                            </span>
                            &mdash; M-Pesa Agent Management System
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include 'layouts/vendor-scripts.php'; ?>
<script>
/* Password toggle */
document.getElementById('toggle-pw').addEventListener('click', function () {
    const pw = document.getElementById('password');
    const ic = this.querySelector('i');
    if (pw.type === 'password') { pw.type = 'text'; ic.className = 'ri-eye-off-line'; }
    else                        { pw.type = 'password'; ic.className = 'ri-eye-line'; }
});

/* Form submit */
document.getElementById('login-form').addEventListener('submit', function (e) {
    const u = document.getElementById('username');
    const p = document.getElementById('password');
    let ok = true;

    [u, p].forEach(el => {
        if (!el.value.trim()) { el.classList.add('is-invalid'); ok = false; }
        else                   { el.classList.remove('is-invalid'); }
    });

    if (!ok) { e.preventDefault(); return; }

    const btn = document.getElementById('login-btn');
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Signing in…';
    btn.disabled = true;
});

/* Auto-focus */
document.addEventListener('DOMContentLoaded', () => document.getElementById('username').focus());

/* Logout success toast */
if (new URLSearchParams(window.location.search).get('logout') === 'success') {
    Swal.fire({ icon: 'success', title: 'Logged Out', text: 'You have been safely logged out.', timer: 2000, showConfirmButton: false });
}

/* Security: clear password on unload */
window.addEventListener('beforeunload', () => document.getElementById('password').value = '');
</script>
</body>
</html>