<?php
declare(strict_types=1);
session_start();
$dbHost = getenv('DB_HOST') ?: 'localhost';
$dbUser = getenv('DB_USER') ?: 'root';
$dbPass = getenv('DB_PASSWORD') ?: '';
$dbName = 'listbnb';

try {
    $pdo = new PDO("mysql:host={$dbHost};dbname={$dbName};charset=utf8mb4", $dbUser, $dbPass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Database connection failed.');window.location.href='admin-dashboard.php';</script></body></html>";
    exit;
}

try {
    $pdo->exec('CREATE TABLE IF NOT EXISTS home_images (
        id INT AUTO_INCREMENT PRIMARY KEY,
        image_path VARCHAR(255) NOT NULL,
        sort_order TINYINT UNSIGNED NOT NULL DEFAULT 1,
        active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
} catch (Throwable $e) {}

$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $uploadDir = __DIR__ . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'home';
    if (!is_dir($uploadDir)) { @mkdir($uploadDir, 0775, true); }

    $files = ['file1','file2','file3'];
    $paths = [];
    foreach ($files as $idx => $key) {
        $name = $_FILES[$key]['name'] ?? '';
        $tmp = $_FILES[$key]['tmp_name'] ?? '';
        $err = (int)($_FILES[$key]['error'] ?? UPLOAD_ERR_NO_FILE);
        if ($err === UPLOAD_ERR_NO_FILE || $name === '' || $tmp === '') { continue; }
        $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
        if (!in_array($ext, ['png','jpg','jpeg'], true)) { continue; }
        $safe = preg_replace('/[^a-zA-Z0-9_\.-]/', '_', pathinfo($name, PATHINFO_FILENAME));
        $final = $safe . '_' . uniqid('', true) . '.' . $ext;
        $dest = $uploadDir . DIRECTORY_SEPARATOR . $final;
        if (@move_uploaded_file($tmp, $dest)) {
            $paths[$idx] = 'uploads/home/' . $final;
        }
    }
    if (count($paths) < 3) {
        $message = 'Please upload at least 3 images (JPG/JPEG/PNG).';
    } else {
        try { $pdo->exec('DELETE FROM home_images'); } catch (Throwable $e) {}
        $sort = 1;
        foreach ($paths as $p) {
            try {
                $st = $pdo->prepare('INSERT INTO home_images (image_path, sort_order, active) VALUES (:path, :ord, 1)');
                $st->execute([':path' => $p, ':ord' => $sort]);
                $sort++;
            } catch (Throwable $e) {}
        }
        $message = 'Home images updated successfully.';
    }
}

$rows = [];
try { $rows = $pdo->query('SELECT id,image_path,sort_order,active,created_at FROM home_images WHERE active=1 ORDER BY sort_order ASC')->fetchAll(); } catch (Throwable $e) { $rows = []; }
?>
<!doctype html>
<html class="no-js" lang="zxx">
<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Home Images - ListBnb Admin</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" type="image/x-icon" href="assets/img/logo/favicon.png">
    <link rel="stylesheet" href="assets/css/bootstrap.css">
    <link rel="stylesheet" href="assets/css/animate.css">
    <link rel="stylesheet" href="assets/css/swiper-bundle.css">
    <link rel="stylesheet" href="assets/css/slick.css">
    <link rel="stylesheet" href="assets/css/magnific-popup.css">
    <link rel="stylesheet" href="assets/css/font-awesome-pro.css">
    <link rel="stylesheet" href="assets/css/spacing.css">
    <link rel="stylesheet" href="assets/css/custom-animation.css">
    <link rel="stylesheet" href="assets/css/main.css">
    <style>
      .admin-layout{display:flex;gap:20px;margin-top:0}
      .tp-profile-area{padding-top:0 !important;padding-bottom:40px !important}
      .tp-header-area.tp-header-inner-style{margin-bottom:0}
      .admin-sidebar{width:280px;background:#fff;border:1px solid var(--border);border-radius:var(--radius);padding:20px;box-shadow:var(--shadow);height:fit-content;position:sticky;top:100px}
      .admin-sidebar .menu-title{font-size:13px;color:var(--text-light);text-transform:uppercase;margin:24px 0 12px;letter-spacing:.05em;padding-left:8px;font-weight:600}
      .admin-sidebar ul{list-style:none;padding:0;margin:0}
      .admin-sidebar li a{display:flex;align-items:center;gap:12px;padding:10px 12px;border-radius:8px;color:var(--text);text-decoration:none;transition:all .2s ease;font-weight:500}
      .admin-sidebar li a:hover,.admin-sidebar li a.active{background:var(--primary-light);color:var(--primary)}
      .admin-sidebar li a i{width:20px;text-align:center;font-size:1.1em}
      .admin-profile{margin-top:14px;border:1px solid #eee;border-radius:14px;padding:12px;display:flex;align-items:center;gap:12px}
      .admin-avatar{width:42px;height:42px;border-radius:10px;background:#f5f7fa;display:flex;align-items:center;justify-content:center;font-weight:600}
      .admin-main{flex:1}
      .section{background:#fff;border:1px solid #eee;border-radius:16px;padding:16px;box-shadow:0 6px 24px rgba(0,0,0,.06)}
      .gallery{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}
      .gallery img{width:100%;height:160px;object-fit:cover;border-radius:10px;border:1px solid #eee}
      .note{font-size:12px;color:#666}
      .header-left{display:flex;align-items:center;gap:12px}
      .admin-headline{font-weight:800;font-size:24px;color:#1f2937}
      .sidebar-card{padding:0}
      .sidebar-card .admin-sidebar{background:transparent;border:none;box-shadow:none;padding:20px}
    </style>
    </head>
<body>
   <header class="tp-header-height">
      <div id="header-sticky" class="tp-header-area tp-header-inner-style">
         <div class="container">
            <div class="row align-items-center">
               <div class="col-xl-3 col-lg-6 col-md-6 col-6">
                  <div class="header-left">
                     <div class="admin-headline">Admin Dashboard</div>
                  </div>
               </div>
               <div class="col-xl-6 col-lg-4 d-none d-xl-block">
                  <div class="tp-header-menu">
                     <nav class="tp-main-menu-content">
                        <ul></ul>
                     </nav>
                  </div>
               </div>
               <div class="col-xl-3 col-lg-6 col-md-6 col-6">
                  <div class="tp-header-right d-flex align-items-center justify-content-end">
                     <div class="tp-header-sign-box d-none d-sm-block">
                        <a href="logout.php"><i class="fa-solid fa-right-from-bracket"></i>Logout</a>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </header>

   <main>
      <div class="tp-profile-area z-index pb-120 pt-60">
         <div class="container">
            <div class="admin-layout">
              <div class="section sidebar-card">
                <aside class="admin-sidebar">
                <div class="menu-title">Menu</div>
                <ul>
                  <li><a href="admin-dashboard.php"><i class="fa-regular fa-grid-2"></i> Dashboard</a></li>
                </ul>
                <div class="menu-title">Product & Order</div>
                <ul>
                  <li><a href="admin-products.php"><i class="fa-regular fa-box"></i> Manage Products</a></li>
                  <li><a href="admin-order-requests.php"><i class="fa-regular fa-cart-shopping"></i> Manage Order Requests</a></li>
                </ul>
                <div class="menu-title">Site Content</div>
                <ul>
                  <li><a href="admin-home-images.php" class="active"><i class="fa-regular fa-image"></i> Home Image</a></li>
                </ul>
                
                </aside>
              </div>
              <section class="admin-main">
                <div class="section mb-20">
                  <h4 class="tp-form-title mb-5">Home Images</h4>
                  <p class="mb-0">Upload at least 3 images to display on the Home slider.</p>
                </div>
                <?php if ($message !== ''): ?>
                  <div class="section" style="border-color:#ffeeba;background:#fff3cd;color:#856404"><?php echo htmlspecialchars($message, ENT_QUOTES); ?></div>
                <?php endif; ?>
                <div class="section mb-20">
                  <h4 class="tp-form-title mb-10">Current Images</h4>
                  <div class="gallery">
                    <?php if (!$rows): ?>
                      <div class="note">No images found</div>
                    <?php else: foreach ($rows as $r): ?>
                      <div>
                        <img src="<?php echo htmlspecialchars($r['image_path'], ENT_QUOTES); ?>" alt="home image"/>
                        <div class="note">Order: <?php echo (int)$r['sort_order']; ?></div>
                      </div>
                    <?php endforeach; endif; ?>
                  </div>
                </div>
                <div class="section">
                  <h4 class="tp-form-title mb-10">Upload Images</h4>
                  <form method="post" enctype="multipart/form-data">
                    <div class="row g-3">
                      <div class="col-md-4">
                        <label class="form-label">Image 1</label>
                        <input type="file" name="file1" accept=".jpg,.jpeg,.png" class="form-control" required>
                      </div>
                      <div class="col-md-4">
                        <label class="form-label">Image 2</label>
                        <input type="file" name="file2" accept=".jpg,.jpeg,.png" class="form-control" required>
                      </div>
                      <div class="col-md-4">
                        <label class="form-label">Image 3</label>
                        <input type="file" name="file3" accept=".jpg,.jpeg,.png" class="form-control" required>
                      </div>
                    </div>
                    <div class="mt-3">
                      <button class="btn btn-primary" type="submit"><i class="fa-regular fa-upload"></i> Save Images</button>
                    </div>
                    <div class="note mt-2">Allowed: JPG, JPEG, PNG. Uploading replaces existing images.</div>
                  </form>
                </div>
              </section>
            </div>
         </div>
      </div>
   </main>

   <script src="assets/js/vendor/jquery.js"></script>
   <script src="assets/js/bootstrap-bundle.js"></script>
   <script src="assets/js/slick.js"></script>
   <script src="assets/js/main.js"></script>
  </body>
  </html>
