<?php
session_start();

$error = "";
$success = "";

/*
|--------------------------------------------------------------------------
| Database Connection
|--------------------------------------------------------------------------
*/
$conn = mysqli_connect("localhost", "root", "", "pos_system");

if (!$conn) {
    die("Database connection failed: " . mysqli_connect_error());
}

/*
|--------------------------------------------------------------------------
| Fetch Shop Settings
|--------------------------------------------------------------------------
*/
$shopLogo = "";
$shopName = "My Shop";
$ownerName = "Shop Owner";
$ownerMobile = "";
$ownerAddress = "";

$shopQuery = "SELECT * FROM shop_settings ORDER BY id ASC LIMIT 1";
$shopResult = mysqli_query($conn, $shopQuery);

if ($shopResult && mysqli_num_rows($shopResult) > 0) {
    $shopRow = mysqli_fetch_assoc($shopResult);
    $shopLogo = $shopRow['shop_logo'] ?? '';
    $shopName = $shopRow['shop_name'] ?? 'My Shop';
    $ownerName = $shopRow['owner_name'] ?? 'Shop Owner';
    $ownerMobile = $shopRow['owner_mobile'] ?? '';
    $ownerAddress = $shopRow['owner_address'] ?? '';
}

/*
|--------------------------------------------------------------------------
| Fetch License Settings
|--------------------------------------------------------------------------
*/
$licenseStatus = "inactive";
$startDate = "";
$renewDate = "";
$expiryDateOnly = date("Y-m-d");
$expiryDateTime = date("Y-m-d 23:59:59");

$licenseQuery = "SELECT * FROM license_settings ORDER BY id ASC LIMIT 1";
$licenseResult = mysqli_query($conn, $licenseQuery);

if ($licenseResult && mysqli_num_rows($licenseResult) > 0) {
    $licenseRow = mysqli_fetch_assoc($licenseResult);
    $licenseStatus = $licenseRow['license_status'] ?? 'inactive';
    $startDate = $licenseRow['start_date'] ?? '';
    $renewDate = $licenseRow['renew_date'] ?? '';
    $expiryDateOnly = $licenseRow['expiry_date'] ?? date("Y-m-d");

    if (!empty($expiryDateOnly)) {
        $expiryDateTime = $expiryDateOnly . " 23:59:59";
    }
}

/*
|--------------------------------------------------------------------------
| Login Process
|--------------------------------------------------------------------------
*/
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');

    if (empty($username) || empty($password)) {
        $error = "Please fill in all fields.";
    } else {
        if ($licenseStatus !== 'active') {
            $error = "License is inactive. Please contact Super Admin.";
        } else {
            $today = date("Y-m-d");

            if (!empty($expiryDateOnly) && $expiryDateOnly < $today) {
                $error = "License has expired. Please renew your license.";
            } else {
                $username = mysqli_real_escape_string($conn, $username);
                $password = mysqli_real_escape_string($conn, $password);

                $query = "SELECT * FROM super_admins WHERE username='$username' AND status='active' LIMIT 1";
                $result = mysqli_query($conn, $query);

                if ($result && mysqli_num_rows($result) == 1) {
                    $row = mysqli_fetch_assoc($result);

                    if ($password == $row['password']) {
                        $_SESSION['admin_id'] = $row['id'];
                        $_SESSION['admin_name'] = $row['full_name'];

                        header("Location: ../Dashboard/dashboard.php");
                        exit();
                    } else {
                        $error = "Invalid password";
                    }
                } else {
                    $error = "User not found or inactive";
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en" id="htmlTag">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>POS Login</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body>

<div class="page-container">
    <div class="page-top-controls">
        <button type="button" class="top-btn" id="languageToggleBtn">
            <i class="bi bi-translate me-1"></i> اردو
        </button>
        <button type="button" class="top-btn" id="themeToggleBtn">
            <i class="bi bi-moon-stars-fill me-1"></i> Dark Mode
        </button>
    </div>

    <div class="container-fluid px-0">
        <div class="row login-wrapper g-0">
            <div class="col-md-6 d-flex align-items-center">
                <div class="left-panel w-100">
                    <div class="brand-badge">SMB Tech Solutions</div>

                    <div class="welcome-header">
                        <div class="welcome-copy">
                            <h1 data-en="Welcome Back!" data-ur="خوش آمدید!">Welcome Back!</h1>
                        </div>

                        <?php if (!empty($shopLogo)): ?>
                            <div class="shop-logo-wrap">
                                <img src="<?php echo htmlspecialchars($shopLogo); ?>" alt="Shop Logo" class="shop-logo">
                            </div>
                        <?php endif; ?>
                    </div>

                    <div class="shop-info-card">
                        <div class="shop-name-main"><?php echo htmlspecialchars($shopName); ?></div>

                        <?php if (!empty($ownerAddress)): ?>
                            <div class="shop-meta-text">
                                <strong data-en="Address:" data-ur="ایڈریس:">Address:</strong>
                                <span><?php echo htmlspecialchars($ownerAddress); ?></span>
                            </div>
                        <?php endif; ?>

                        <?php if (!empty($ownerName)): ?>
                            <div class="shop-meta-text">
                                <strong data-en="Owner:" data-ur="مالک:">Owner:</strong>
                                <span><?php echo htmlspecialchars($ownerName); ?></span>
                            </div>
                        <?php endif; ?>

                        <?php if (!empty($ownerMobile)): ?>
                            <div class="shop-meta-text">
                                <strong data-en="Mobile:" data-ur="موبائل:">Mobile:</strong>
                                <span><?php echo htmlspecialchars($ownerMobile); ?></span>
                            </div>
                        <?php endif; ?>
                    </div>

                    <div class="expiry-card">
                        <div class="expiry-title">
                            <i class="bi bi-calendar-check-fill"></i>
                            <span data-en="Software Validity Status" data-ur="سافٹ ویئر ویلیڈیٹی اسٹیٹس">Software Validity Status</span>
                        </div>

                        <div class="expiry-grid">
                            <div class="expiry-box">
                                <div class="expiry-label" data-en="License Status" data-ur="لائسنس اسٹیٹس">License Status</div>
                                <div class="expiry-value" id="licenseStatusText"><?php echo ucfirst(htmlspecialchars($licenseStatus)); ?></div>
                            </div>

                            <div class="expiry-box">
                                <div class="expiry-label" data-en="Expiry Date" data-ur="ایکسپائری ڈیٹ">Expiry Date</div>
                                <div class="expiry-value" id="expiryDateText">--</div>
                            </div>

                            <div class="expiry-box">
                                <div class="expiry-label" data-en="Remaining Time" data-ur="باقی وقت">Remaining Time</div>
                                <div class="expiry-value" id="remainingTime">--</div>
                            </div>
                        </div>

                        <div class="expiry-note" id="expiryNote"
                             data-en="Renew before expiry to avoid any interruption in access."
                             data-ur="ایکسیس میں رکاوٹ سے بچنے کے لیے ایکسپائری سے پہلے تجدید کروائیں۔">
                            Renew before expiry to avoid any interruption in access.
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-md-6">
                <div class="right-panel">
                    <div class="icon-circle">
                        <i class="bi bi-shield-lock-fill"></i>
                    </div>

                    <div class="text-center">
                        <h2 class="login-title" data-en="Login" data-ur="لاگ ان">Login</h2>
                        <p class="login-subtitle" data-en="Enter your account details" data-ur="اپنی اکاؤنٹ تفصیلات درج کریں">Enter your account details</p>
                    </div>

                    <?php if (!empty($error)): ?>
                        <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
                    <?php endif; ?>

                    <?php if (!empty($success)): ?>
                        <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
                    <?php endif; ?>

                    <form method="POST" action="" id="loginForm" novalidate>
                        <div class="mb-3">
                            <label class="form-label" data-en="Username" data-ur="یوزرنیم">Username</label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="bi bi-person-fill"></i></span>
                                <input
                                    type="text"
                                    name="username"
                                    id="username"
                                    class="form-control"
                                    placeholder="Enter username"
                                    data-placeholder-en="Enter username"
                                    data-placeholder-ur="یوزرنیم درج کریں"
                                    required
                                    autofocus
                                    value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>"
                                >
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label" data-en="Password" data-ur="پاس ورڈ">Password</label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="bi bi-key-fill"></i></span>
                                <input
                                    type="password"
                                    name="password"
                                    id="password"
                                    class="form-control"
                                    placeholder="Enter password"
                                    data-placeholder-en="Enter password"
                                    data-placeholder-ur="پاس ورڈ درج کریں"
                                    required
                                >
                                <button class="btn btn-outline-secondary toggle-password-btn" type="button" id="togglePassword">
                                    <i class="bi bi-eye-fill"></i>
                                </button>
                            </div>
                        </div>

                        <div class="d-grid mt-3">
                            <button type="submit" class="btn btn-login" data-en="Login Now" data-ur="ابھی لاگ ان کریں">Login Now</button>
                        </div>
                    </form>

                    <div class="login-side-note">
                        <p data-en="Powered by SMB Tech Solutions — delivering professional, secure, and modern business software solutions with a focus on performance, reliability, and long-term support."
                           data-ur="ایس ایم بی ٹیک سلوشنز کے ذریعے تیار کردہ — پیشہ ورانہ، محفوظ، اور جدید بزنس سافٹ ویئر سلوشنز جو پرفارمنس، اعتماد، اور طویل مدتی سپورٹ پر فوکس کرتے ہیں۔">
                            Powered by <span class="smb-highlight">SMB Tech Solutions</span> — delivering professional, secure, and modern business software solutions with a focus on performance, reliability, and long-term support.
                        </p>

                        <p data-en="Please review your software validity before login. Renew on time to avoid interruption and keep your business operations running smoothly."
                           data-ur="لاگ ان سے پہلے اپنے سافٹ ویئر کی مدت ضرور دیکھیں۔ وقت پر ریچارج کریں تاکہ رکاوٹ نہ آئے اور آپ کے بزنس آپریشنز آسانی سے چلتے رہیں۔">
                            Please review your software validity before login. Renew on time to avoid interruption and keep your business operations running smoothly.
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    window.posConfig = {
        expiryDateTime: "<?php echo $expiryDateTime; ?>"
    };
</script>
<script src="assets/js/script.js"></script>

</body>
</html>