<?php
session_start();

if (!isset($_SESSION['admin_id'])) {
    header("Location: ../Login/login.php");
    exit();
}

$conn = mysqli_connect("localhost", "root", "", "pos_system");

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

$adminName = $_SESSION['admin_name'] ?? 'Super Admin';
$page = $_GET['page'] ?? 'dashboard';
$successMessage = "";

/* =========================
   PAGE TITLES
========================= */
$pageTitles = [
    'dashboard' => 'Dashboard',
    'configuration' => 'Configuration',
    'licensing' => 'Licensing'
];

$currentTitle = $pageTitles[$page] ?? 'Dashboard';

/* =========================
   SUCCESS MESSAGE
========================= */
if (isset($_GET['success'])) {
    if ($_GET['success'] === 'config') {
        $successMessage = 'Configuration updated successfully!';
    } elseif ($_GET['success'] === 'license') {
        $successMessage = 'License updated successfully!';
    }
}

/* =========================
   FETCH SHOP SETTINGS
========================= */
$shopQuery = mysqli_query($conn, "SELECT * FROM shop_settings ORDER BY id ASC LIMIT 1");
$shop = ($shopQuery && mysqli_num_rows($shopQuery) > 0) ? mysqli_fetch_assoc($shopQuery) : null;

/* =========================
   FETCH LICENSE SETTINGS
========================= */
$licenseQuery = mysqli_query($conn, "SELECT * FROM license_settings ORDER BY id ASC LIMIT 1");
$license = ($licenseQuery && mysqli_num_rows($licenseQuery) > 0) ? mysqli_fetch_assoc($licenseQuery) : null;

/* =========================
   SAVE CONFIGURATION
========================= */
if (isset($_POST['save_config'])) {
    $shop_logo = trim($_POST['shop_logo'] ?? '');
    $shop_name = trim($_POST['shop_name'] ?? '');
    $owner_name = trim($_POST['owner_name'] ?? '');
    $owner_mobile = trim($_POST['owner_mobile'] ?? '');
    $owner_address = trim($_POST['owner_address'] ?? '');

    $shop_logo = mysqli_real_escape_string($conn, $shop_logo);
    $shop_name = mysqli_real_escape_string($conn, $shop_name);
    $owner_name = mysqli_real_escape_string($conn, $owner_name);
    $owner_mobile = mysqli_real_escape_string($conn, $owner_mobile);
    $owner_address = mysqli_real_escape_string($conn, $owner_address);

    if ($shop) {
        $shopId = (int)$shop['id'];

        mysqli_query($conn, "UPDATE shop_settings SET 
            shop_logo='$shop_logo',
            shop_name='$shop_name',
            owner_name='$owner_name',
            owner_mobile='$owner_mobile',
            owner_address='$owner_address',
            updated_at=NOW()
            WHERE id=$shopId");
    } else {
        mysqli_query($conn, "INSERT INTO shop_settings 
            (shop_logo, shop_name, owner_name, owner_mobile, owner_address, created_at, updated_at) 
            VALUES 
            ('$shop_logo', '$shop_name', '$owner_name', '$owner_mobile', '$owner_address', NOW(), NOW())");
    }

    header("Location: dashboard.php?page=configuration&success=config");
    exit();
}

/* =========================
   SAVE LICENSE
========================= */
if (isset($_POST['save_license'])) {
    $license_status = trim($_POST['license_status'] ?? '');
    $start_date = trim($_POST['start_date'] ?? '');
    $expiry_date = trim($_POST['expiry_date'] ?? '');
    $renew_date = trim($_POST['renew_date'] ?? '');

    $license_status = mysqli_real_escape_string($conn, $license_status);
    $start_date = mysqli_real_escape_string($conn, $start_date);
    $expiry_date = mysqli_real_escape_string($conn, $expiry_date);
    $renew_date = mysqli_real_escape_string($conn, $renew_date);

    if ($license) {
        $licenseId = (int)$license['id'];

        mysqli_query($conn, "UPDATE license_settings SET 
            license_status='$license_status',
            start_date='$start_date',
            expiry_date='$expiry_date',
            renew_date='$renew_date',
            updated_at=NOW()
            WHERE id=$licenseId");
    } else {
        mysqli_query($conn, "INSERT INTO license_settings 
            (license_status, start_date, expiry_date, renew_date, created_at, updated_at) 
            VALUES 
            ('$license_status', '$start_date', '$expiry_date', '$renew_date', NOW(), NOW())");
    }

    header("Location: dashboard.php?page=licensing&success=license");
    exit();
}
?>
<!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 Dashboard</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/dashboard.css">
</head>
<body>

<div class="dashboard-layout">
    <aside class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <div class="brand-title">SMB Tech Solutions</div>
            <div class="brand-subtitle">POS Management System</div>
        </div>

        <div class="sidebar-user">
            <div class="user-icon">
                <i class="bi bi-person-circle"></i>
            </div>
            <div class="user-info">
                <div class="user-role">Logged in as</div>
                <div class="user-name"><?php echo htmlspecialchars($adminName); ?></div>
            </div>
        </div>

        <nav class="sidebar-nav">
            <a href="dashboard.php?page=dashboard" class="nav-link-item <?php echo ($page === 'dashboard') ? 'active' : ''; ?>">
                <span class="nav-icon"><i class="bi bi-grid-1x2-fill"></i></span>
                <span class="nav-text">Dashboard</span>
            </a>

            <a href="dashboard.php?page=configuration" class="nav-link-item <?php echo ($page === 'configuration') ? 'active' : ''; ?>">
                <span class="nav-icon"><i class="bi bi-gear-fill"></i></span>
                <span class="nav-text">Configuration</span>
            </a>

            <a href="dashboard.php?page=licensing" class="nav-link-item <?php echo ($page === 'licensing') ? 'active' : ''; ?>">
                <span class="nav-icon"><i class="bi bi-shield-check"></i></span>
                <span class="nav-text">Licensing</span>
            </a>

            <a href="logout.php" class="nav-link-item logout-link">
                <span class="nav-icon"><i class="bi bi-box-arrow-right"></i></span>
                <span class="nav-text">Logout</span>
            </a>
        </nav>
    </aside>

    <main class="main-panel">
        <div class="topbar">
            <div class="topbar-left">
                <button class="menu-toggle-btn d-lg-none" id="menuToggleBtn" type="button">
                    <i class="bi bi-list"></i>
                </button>
                <div>
                    <h1 class="page-title"><?php echo htmlspecialchars($currentTitle); ?></h1>
                    <p class="page-subtitle">Welcome back, <?php echo htmlspecialchars($adminName); ?></p>
                </div>
            </div>

            <div class="topbar-right">
                <button type="button" class="theme-btn" id="themeToggleBtn">
                    <i class="bi bi-moon-stars-fill me-1"></i> Dark Mode
                </button>
            </div>
        </div>

        <div class="content-area">

            <?php if (!empty($successMessage)): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="bi bi-check-circle-fill me-2"></i>
                    <?php echo htmlspecialchars($successMessage); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>

            <?php if ($page === 'dashboard'): ?>

                <div class="content-card">
                    <div class="content-card-header">
                        <h3>About SMB Tech Solutions</h3>
                    </div>
                    <div class="content-card-body">
                        <p><strong>Company Name:</strong> SMB Tech Solutions</p>
                        <p><strong>System:</strong> POS Management System</p>
                        <p><strong>Admin:</strong> <?php echo htmlspecialchars($adminName); ?></p>

                        <p>
                            SMB Tech Solutions provides professional, secure, and modern business software solutions.
                            This dashboard is designed for Super Admin configuration and license management.
                        </p>

                        <p class="mb-0">
                            Use the Configuration section to manage shop details, and the Licensing section to control software validity.
                        </p>
                    </div>
                </div>

            <?php elseif ($page === 'configuration'): ?>

                <div class="content-card">
                    <div class="content-card-header">
                        <h3>Configuration Settings</h3>
                    </div>

                    <div class="content-card-body">
                        <form method="POST" action="">
                            <div class="mb-3">
                                <label class="form-label">Shop Logo</label>
                                <input
                                    type="text"
                                    name="shop_logo"
                                    class="form-control"
                                    placeholder="Enter shop logo path"
                                    value="<?php echo htmlspecialchars($shop['shop_logo'] ?? ''); ?>"
                                >
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Shop Name</label>
                                <input
                                    type="text"
                                    name="shop_name"
                                    class="form-control"
                                    placeholder="Enter shop name"
                                    value="<?php echo htmlspecialchars($shop['shop_name'] ?? ''); ?>"
                                >
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Owner Name</label>
                                <input
                                    type="text"
                                    name="owner_name"
                                    class="form-control"
                                    placeholder="Enter owner name"
                                    value="<?php echo htmlspecialchars($shop['owner_name'] ?? ''); ?>"
                                >
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Owner Mobile</label>
                                <input
                                    type="text"
                                    name="owner_mobile"
                                    class="form-control"
                                    placeholder="Enter mobile number"
                                    value="<?php echo htmlspecialchars($shop['owner_mobile'] ?? ''); ?>"
                                >
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Owner Address</label>
                                <textarea
                                    name="owner_address"
                                    class="form-control"
                                    rows="4"
                                    placeholder="Enter owner address"
                                ><?php echo htmlspecialchars($shop['owner_address'] ?? ''); ?></textarea>
                            </div>

                            <button type="submit" name="save_config" class="btn btn-success">
                                <i class="bi bi-check-circle-fill me-1"></i> Save
                            </button>
                        </form>
                    </div>
                </div>

            <?php elseif ($page === 'licensing'): ?>

                <div class="content-card">
                    <div class="content-card-header">
                        <h3>License Management</h3>
                    </div>

                    <div class="content-card-body">
                        <form method="POST" action="">
                            <div class="mb-3">
                                <label class="form-label">License Status</label>
                                <select name="license_status" class="form-control">
                                    <option value="active" <?php echo (($license['license_status'] ?? '') === 'active') ? 'selected' : ''; ?>>active</option>
                                    <option value="inactive" <?php echo (($license['license_status'] ?? '') === 'inactive') ? 'selected' : ''; ?>>inactive</option>
                                </select>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Start Date</label>
                                <input
                                    type="date"
                                    name="start_date"
                                    class="form-control"
                                    value="<?php echo htmlspecialchars($license['start_date'] ?? ''); ?>"
                                >
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Expiry Date</label>
                                <input
                                    type="date"
                                    name="expiry_date"
                                    class="form-control"
                                    value="<?php echo htmlspecialchars($license['expiry_date'] ?? ''); ?>"
                                >
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Renew Date</label>
                                <input
                                    type="date"
                                    name="renew_date"
                                    class="form-control"
                                    value="<?php echo htmlspecialchars($license['renew_date'] ?? ''); ?>"
                                >
                            </div>

                            <button type="submit" name="save_license" class="btn btn-danger">
                                <i class="bi bi-save-fill me-1"></i> Save
                            </button>
                        </form>
                    </div>
                </div>

            <?php endif; ?>

        </div>
    </main>
</div>

<div class="sidebar-overlay" id="sidebarOverlay"></div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="assets/js/dashboard.js"></script>

</body>
</html>