<?php
session_start();
require_once '../config/db_connect.php';

$error = '';
$username = '';
$password = '';
$shop_id = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    $shop_id = isset($_POST['shop_id']) ? intval($_POST['shop_id']) : null;

    if ($username && $password) {
        $stmt = $pdo->prepare("SELECT u.*, s.name AS shop_name 
                               FROM users u 
                               LEFT JOIN shops s ON u.shop_id = s.id 
                               WHERE username = ?");
        $stmt->execute([$username]);
        $user = $stmt->fetch();

        if ($user && password_verify($password, $user['password_hash'])) {
            // Check if admin needs to select shop
            if ($user['role'] === 'admin' && !$shop_id) {
                $error = "Please select a shop.";
                // Note: We keep the values already in variables
            } else {
                $_SESSION['user'] = [
                    'id' => $user['id'],
                    'username' => $user['username'],
                    'fullname' => $user['fullname'],
                    'role' => $user['role'],
                    'shop_id' => $user['role'] === 'admin' ? $shop_id : $user['shop_id'],
                    'shop_name' => $user['role'] === 'admin'
                        ? getShopName($shop_id, $pdo)
                        : $user['shop_name']
                ];

                header("Location: ../modules/dashboard.php");
                exit;
            }
        } else {
            $error = "Invalid username or password.";
            // Keep values already in variables
        }
    } else {
        $error = "Please enter both username and password.";
        // Keep values already in variables
    }
}

function getShopName($shop_id, $pdo){
    $stmt = $pdo->prepare("SELECT name FROM shops WHERE id = ?");
    $stmt->execute([$shop_id]);
    $shop = $stmt->fetch();
    return $shop ? $shop['name'] : '';
}

$shops = $pdo->query("SELECT id, name FROM shops")->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login | Pharmacy System</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="../libraries/bootstrap.css">
<link rel="icon" href="../assets/img/favicon.jpg">

<style>
body {
    background: linear-gradient(135deg, #ede9fe, #e0e7ff);
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    font-family: 'Segoe UI', Tahoma, sans-serif;
}

.login-box {
    background: #ffffff;
    width: 420px;
    padding: 35px;
    border-radius: 14px;
    box-shadow: 0 20px 40px rgba(76, 29, 149, 0.15);
}

.login-box h3 {
    text-align: center;
    color: #4c1d95;
    font-weight: 700;
    margin-bottom: 5px;
}

.login-box p.subtitle {
    text-align: center;
    color: #6b7280;
    font-size: 14px;
    margin-bottom: 25px;
}

.form-control {
    border-radius: 10px;
    padding: 10px 14px;
}

.form-control:focus {
    border-color: #6d28d9;
    box-shadow: 0 0 0 0.15rem rgba(109, 40, 217, 0.25);
}

label {
    font-weight: 600;
    color: #312e81;
}

.btn-login {
    background: linear-gradient(135deg, #6d28d9, #2563eb);
    border: none;
    color: white;
    font-weight: 600;
    padding: 12px;
    border-radius: 10px;
    transition: all 0.3s ease;
}

.btn-login:hover {
    background: linear-gradient(135deg, #5b21b6, #1d4ed8);
    transform: translateY(-1px);
}

.alert {
    border-radius: 10px;
}

.footer-text {
    text-align: center;
    font-size: 12px;
    color: #6b7280;
    margin-top: 20px;
}
</style>
</head>

<body>

<div class="login-box">
    <h3>Pharmacy Management System</h3>
    <p class="subtitle">Secure access to your workspace</p>

    <?php if ($error): ?>
        <div class="alert alert-danger text-center">

            <?= htmlspecialchars($error) ?>
        </div>
    <?php endif; ?>

    <form method="POST">
        <div class="form-group mb-3">
            <label>Username</label>
            <input type="text" name="username" class="form-control" 
                   value="<?= htmlspecialchars($username) ?>" 
                   required autofocus>
        </div>

        <div class="form-group mb-3">
            <label>Password</label>
            <input type="password" name="password" class="form-control" 
                   value="<?= htmlspecialchars($password) ?>" 
                   required>
        </div>

        <?php 
        // Determine if we need to show shop selection
        $showShopSelect = false;
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($username)) {
            // Check if this username belongs to an admin
            $checkUser = $pdo->prepare("SELECT role FROM users WHERE username = ?");
            $checkUser->execute([$username]);
            $userData = $checkUser->fetch();
            $showShopSelect = ($userData && $userData['role'] === 'admin');
        }
        
        if ($showShopSelect): ?>
            <div class="form-group mb-3">
                <label>Select Shop</label>
                <select name="shop_id" class="form-control" required>
                    <option value="">-- Choose Shop --</option>
                    <?php foreach ($shops as $shop): ?>
                        <option value="<?= $shop['id'] ?>" 
                            <?= ($shop_id == $shop['id']) ? 'selected' : '' ?>>
                            <?= htmlspecialchars($shop['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
        <?php endif; ?>

        <button type="submit" class="btn btn-login w-100 mt-3">
            Login
        </button>
    </form>

    <div class="footer-text">
        © <?= date('Y') ?> Pharmacy System
    </div>
</div>

</body>
</html>