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

if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: ../login.php');
    exit();
}

// Create gallery table
$pdo->exec("CREATE TABLE IF NOT EXISTS gallery (
  id INT AUTO_INCREMENT PRIMARY KEY,
  title VARCHAR(200) NULL,
  image_path VARCHAR(255) NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

$success=''; $error='';

function saveImage(?array $file): ?string {
  if (!$file || empty($file['name'])) return null;
  if (!is_uploaded_file($file['tmp_name'])) return null;
  $allowed = ['image/jpeg'=>'jpg','image/png'=>'png','image/gif'=>'gif','image/jpg'=>'jpg'];
  $finfo = finfo_open(FILEINFO_MIME_TYPE);
  $mime  = finfo_file($finfo, $file['tmp_name']);
  finfo_close($finfo);
  if (!isset($allowed[$mime])) return null;
  $ext = $allowed[$mime];
  $dir = dirname(__DIR__) . '/uploads/gallery';
  if (!is_dir($dir)) { @mkdir($dir, 0777, true); }
  $name = 'gal_' . uniqid() . '.' . $ext;
  $dest = $dir . '/' . $name;
  if (move_uploaded_file($file['tmp_name'], $dest)) {
    return 'uploads/gallery/' . $name;
  }
  return null;
}

// Upload
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['add_image'])) {
  $title = trim($_POST['title'] ?? '');
  $img = saveImage($_FILES['image'] ?? null);
  if ($img) {
    $stmt=$pdo->prepare('INSERT INTO gallery (title, image_path) VALUES (?, ?)');
    $stmt->execute([$title, $img]);
    $success='ছবি যুক্ত হয়েছে';
  } else {
    $error='ছবি আপলোড ব্যর্থ বা সমর্থিত নয়';
  }
}

// Delete
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['delete_id'])) {
  $id=(int)$_POST['delete_id'];
  $row=$pdo->prepare('SELECT image_path FROM gallery WHERE id=?');
  $row->execute([$id]);
  $cur=$row->fetch(PDO::FETCH_ASSOC)?:[];
  if ($cur && !empty($cur['image_path'])){
    $path=dirname(__DIR__).'/'.$cur['image_path'];
    if (is_file($path)) { @unlink($path); }
  }
  $pdo->prepare('DELETE FROM gallery WHERE id=?')->execute([$id]);
  $success='ছবি মুছে ফেলা হয়েছে';
}

// Fetch
$items=$pdo->query('SELECT * FROM gallery ORDER BY id DESC')->fetchAll(PDO::FETCH_ASSOC);
?>
<html lang="bn">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>গ্যালারি ম্যানেলমেন্ট</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
  <style>
    body {
      font-family: 'Hind Siliguri', sans-serif;
      background: #f5f7fa;
    }
    
    .jb-navbar {
      background: linear-gradient(135deg, #006747 0%, #004d35 100%) !important;
      box-shadow: 0 4px 20px rgba(0, 103, 71, 0.3);
      border-bottom: 3px solid #F42A41;
    }
    
    .jb-navbar .navbar-brand {
      color: #fff !important;
      font-weight: 800;
      text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
    }
    
    .jb-navbar .nav-link {
      color: rgba(255, 255, 255, 0.9) !important;
      font-weight: 600;
    }
    
    .jb-navbar .nav-link:hover {
      color: #FFD700 !important;
    }
    
    .card {
      border: 0;
      border-radius: 14px;
      box-shadow: 0 10px 25px rgba(0,103,71,0.1);
      border-top: 4px solid #006747;
      transition: all 0.3s ease;
    }
    
    .card:hover {
      transform: translateY(-5px);
      box-shadow: 0 15px 35px rgba(0,103,71,0.2);
      border-top-color: #F42A41;
    }
    
    .card-header {
      background: linear-gradient(135deg, #006747 0%, #004d35 100%);
      color: #fff;
      font-weight: 600;
      border-bottom: 2px solid #F42A41;
      border-radius: 14px 14px 0 0 !important;
    }
    
    .btn-primary {
      background: linear-gradient(135deg, #006747 0%, #004d35 100%);
      border: none;
      font-weight: 600;
    }
    
    .btn-primary:hover {
      background: linear-gradient(135deg, #004d35 0%, #006747 100%);
      transform: translateY(-2px);
      box-shadow: 0 5px 15px rgba(0, 103, 71, 0.4);
    }
    
    .btn-outline-danger {
      border-color: #F42A41;
      color: #F42A41;
      font-weight: 600;
    }
    
    .btn-outline-danger:hover {
      background: #F42A41;
      border-color: #F42A41;
    }
    
    .form-control:focus {
      border-color: #006747;
      box-shadow: 0 0 0 0.25rem rgba(0, 103, 71, 0.15);
    }
    
    .gallery-image-card {
      border: 3px solid transparent;
      transition: all 0.3s ease;
    }
    
    .gallery-image-card:hover {
      border-color: #F42A41;
      transform: scale(1.05);
    }
    
    .gallery-image-card img {
      height: 150px;
      object-fit: cover;
    }
    
    .alert-success {
      background: #e8f5e9;
      border-left: 4px solid #28a745;
      color: #155724;
    }
    
    .alert-danger {
      background: #ffebee;
      border-left: 4px solid #F42A41;
      color: #c62828;
    }
  </style>
</head>
<body>
  <nav class="navbar navbar-expand-lg navbar-dark jb-navbar">
    <div class="container-fluid">
      <a class="navbar-brand" href="../index.php"><i class="fas fa-graduation-cap"></i> গ্যালারি ম্যানেজমেন্ট</a>
      <div class="navbar-nav ms-auto">
        <a class="nav-link" href="../index.php"><i class="fas fa-home"></i> হোম</a>
        <a class="nav-link" href="../logout.php"><i class="fas fa-sign-out-alt"></i> লগআউট</a>
      </div>
    </div>
  </nav>

  <div class="container-fluid mt-4">
    <?php if ($success): ?><div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div><?php endif; ?>
    <?php if ($error): ?><div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div><?php endif; ?>

    <div class="row g-3">
      <div class="col-lg-4">
        <div class="card">
          <div class="card-header"><strong>নতুন ছবি যোগ</strong></div>
          <div class="card-body">
            <form method="post" enctype="multipart/form-data">
              <div class="mb-2">
                <label class="form-label">শিরোনাম (ঐচ্ছিক)</label>
                <input class="form-control" name="title">
              </div>
              <div class="mb-3">
                <label class="form-label">ছবি</label>
                <input type="file" class="form-control" name="image" accept="image/*" required>
              </div>
              <button class="btn btn-primary" name="add_image"><i class="fas fa-plus"></i> যোগ করুন</button>
            </form>
          </div>
        </div>
      </div>

      <div class="col-lg-8">
        <div class="card">
          <div class="card-header"><strong>গ্যালারি</strong></div>
          <div class="card-body">
            <div class="row g-3">
              <?php if (empty($items)): ?>
                <div class="col-12 text-center text-muted">কোন ছবি নেই</div>
              <?php else: foreach ($items as $it): ?>
                <div class="col-6 col-md-4 col-lg-3">
                  <div class="card h-100 gallery-image-card">
                    <img src="../<?php echo htmlspecialchars($it['image_path']); ?>" class="card-img-top" alt="">
                    <div class="card-body p-2">
                      <div class="small fw-semibold text-truncate" title="<?php echo htmlspecialchars($it['title'] ?: ''); ?>"><?php echo htmlspecialchars($it['title'] ?: ''); ?></div>
                    </div>
                    <div class="card-footer p-2 text-end">
                      <form method="post" onsubmit="return confirm('মুছতে নিশ্চিত?');">
                        <input type="hidden" name="delete_id" value="<?php echo (int)$it['id']; ?>">
                        <button class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button>
                      </form>
                    </div>
                  </div>
                </div>
              <?php endforeach; endif; ?>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>
</html>