<?php
session_start();
if (!isset($_SESSION['loggedin'])) {
    header('Location: login.php');
    exit();
}

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/camera_settings_model.php';

$pdo = getPDO();

/**
 * در صورتی‌که ثابت در فایل مدل تعریف نشده باشد، همین‌جا مقداردهی می‌شود
 * تا از Undefined constant جلوگیری گردد.
 */
if (!defined('ALLOWED_FRAMESIZES')) {
    define('ALLOWED_FRAMESIZES', [
        'VGA'  => '640 × 480',
        'SVGA' => '800 × 600',
        'XGA'  => '1024 × 768',
        'SXGA' => '1280 × 1024',
        'UXGA' => '1600 × 1200',
    ]);
}

/**
 * نرمال‌سازی مقدار اندازهٔ فریم (هم برای ورودی فرم و هم داده‌های ذخیره‌شده)
 */
function normalizeFrameSize(?string $value): ?string
{
    if ($value === null) {
        return null;
    }
    $trimmed = trim($value);
    if ($trimmed === '') {
        return null;
    }

    $upper = function_exists('mb_strtoupper')
        ? mb_strtoupper($trimmed, 'UTF-8')
        : strtoupper($trimmed);

    if (array_key_exists($upper, ALLOWED_FRAMESIZES)) {
        return $upper;
    }

    $resolutionKey = strtoupper(str_replace(['×', '*', ' '], ['x', 'x', ''], $trimmed));
    $resMap = [
        '640X480'   => 'VGA',
        '800X600'   => 'SVGA',
        '1024X768'  => 'XGA',
        '1280X1024' => 'SXGA',
        '1600X1200' => 'UXGA',
    ];

    return $resMap[$resolutionKey] ?? null;
}

// Flash helpers
function flash_add(string $key, string $type, string $message): void {
    $_SESSION['flash'][$key] = ['type' => $type, 'message' => $message];
}
function flash_get(string $key): ?array {
    if (isset($_SESSION['flash'][$key])) {
        $msg = $_SESSION['flash'][$key];
        unset($_SESSION['flash'][$key]);
        return $msg;
    }
    return null;
}

// Handle camera settings POST (PRG)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_camera') {
    $deviceId = trim($_POST['device_id'] ?? '');
    if ($deviceId === '') {
        flash_add('global', 'error', 'شناسه دستگاه ارسال نشده است.');
        header('Location: gallery.php');
        exit();
    }

    $frameSizeRaw = $_POST['frame_size'] ?? ($_POST['framesize'] ?? null);
    $normalizedFrameSize = normalizeFrameSize($frameSizeRaw);

    $payload = [
        'interval_minutes' => $_POST['interval_minutes'] ?? null,
        'quality'          => $_POST['quality'] ?? null,
        'frame_size'       => $normalizedFrameSize,
        'capture_enabled'  => isset($_POST['capture_enabled']) ? '1' : '0',
    ];

    try {
        $result = saveCameraSettings($pdo, $deviceId, $payload);
        if ($result['ok']) {
            flash_add("cam-$deviceId", 'success', 'تنظیمات دستگاه با موفقیت ذخیره شد.');
        } else {
            $fieldAliases = [
                'frame_size' => 'اندازه فریم',
                'framesize'  => 'اندازه فریم',
                'quality'    => 'کیفیت JPEG',
                'interval_minutes' => 'بازه زمانی',
                'capture_enabled'  => 'فعال‌سازی کپچر',
            ];
            $errText = 'ذخیره تنظیمات با خطا مواجه شد: ';
            foreach ($result['errors'] as $field => $msg) {
                $label = $fieldAliases[$field] ?? $field;
                $errText .= "[$label] $msg؛ ";
            }
            flash_add("cam-$deviceId", 'error', rtrim($errText, '؛ '));
        }
    } catch (Throwable $e) {
        flash_add("cam-$deviceId", 'error', 'خطای داخلی هنگام ذخیره تنظیمات.');
    }

    header('Location: gallery.php#cam-' . urlencode($deviceId));
    exit();
}

// ---------------------
// گالری تصاویر (کد اصلی قبلی شما)
// ---------------------

$files = glob('uploads/*.{jpg,jpeg,png,gif}', GLOB_BRACE) ?: [];

$categoryMap = [
    'ALL'       => 'همه تصاویر',
    'ATLASI'    => 'اطلسی',
    'MOLASADRA' => 'ملاصدرا',
    'SAHELI'    => 'ساحلی',
    'NAMAZI'    => 'نمازی',
    'MALIABAD'  => 'معالی‌آباد',
    'OTHER'     => 'سایر',
];

function convertDigits($value, string $to = 'fa'): string
{
    $en = ['0','1','2','3','4','5','6','7','8','9'];
    $fa = ['۰','۱','۲','۳','۴','۵','۶','۷','۸','۹'];
    return str_replace($to === 'fa' ? $en : $fa, $to === 'fa' ? $fa : $en, (string)$value);
}

function toPersianDigits($value): string
{
    return convertDigits($value, 'fa');
}

function toEnglishDigits($value): string
{
    return convertDigits($value, 'en');
}

function gregorian_to_jalali(int $gy, int $gm, int $gd): array
{
    $gDays = [31,28,31,30,31,30,31,31,30,31,30,31];
    $jDays = [31,31,31,31,31,31,30,30,30,30,30,29];

    $gy -= 1600;
    $gm -= 1;
    $gd -= 1;

    $gDayNo = 365 * $gy + intdiv($gy + 3, 4) - intdiv($gy + 99, 100) + intdiv($gy + 399, 400);
    for ($i = 0; $i < $gm; $i++) {
        $gDayNo += $gDays[$i];
    }
    if ($gm > 1 && (($gy % 4 === 0 && $gy % 100 !== 0) || ($gy % 400 === 0))) {
        $gDayNo++;
    }
    $gDayNo += $gd;

    $jDayNo = $gDayNo - 79;
    $jNp = intdiv($jDayNo, 12053);
    $jDayNo %= 12053;

    $jy = 979 + 33 * $jNp + 4 * intdiv($jDayNo, 1461);
    $jDayNo %= 1461;

    if ($jDayNo >= 366) {
        $jy += intdiv($jDayNo - 1, 365);
        $jDayNo = ($jDayNo - 1) % 365;
    }

    $i = 0;
    while ($i < 11 && $jDayNo >= $jDays[$i]) {
        $jDayNo -= $jDays[$i];
        $i++;
    }

    $jm = $i + 1;
    $jd = $jDayNo + 1;

    return [$jy, $jm, $jd];
}

function jalali_to_gregorian(int $jy, int $jm, int $jd): array
{
    $gDays = [31,28,31,30,31,30,31,31,30,31,30,31];
    $jDays = [31,31,31,31,31,31,30,30,30,30,30,29];

    $jy -= 979;
    $jm -= 1;
    $jd -= 1;

    $jDayNo = 365 * $jy + intdiv($jy, 33) * 8 + intdiv(($jy % 33) + 3, 4);
    for ($i = 0; $i < $jm; $i++) {
        $jDayNo += $jDays[$i];
    }
    $jDayNo += $jd;

    $gDayNo = $jDayNo + 79;

    $gy = 1600 + 400 * intdiv($gDayNo, 146097);
    $gDayNo %= 146097;

    $leap = true;
    if ($gDayNo >= 36525) {
        $gDayNo--;
        $gy += 100 * intdiv($gDayNo, 36524);
        $gDayNo %= 36524;

        if ($gDayNo >= 365) {
            $gDayNo++;
        } else {
            $leap = false;
        }
    }

    $gy += 4 * intdiv($gDayNo, 1461);
    $gDayNo %= 1461;

    if ($gDayNo >= 366) {
        $leap = false;
        $gDayNo--;
        $gy += intdiv($gDayNo, 365);
        $gDayNo %= 365;
    }

    $i = 0;
    while ($i < 11 && $gDayNo >= $gDays[$i] + ($i === 1 && $leap ? 1 : 0)) {
        $gDayNo -= $gDays[$i] + ($i === 1 && $leap ? 1 : 0);
        $i++;
    }

    $gm = $i + 1;
    $gd = $gDayNo + 1;

    return [$gy, $gm, $gd];
}

function toJalaliString(int $timestamp): string
{
    $gy = (int)date('Y', $timestamp);
    $gm = (int)date('n', $timestamp);
    $gd = (int)date('j', $timestamp);
    [$jy, $jm, $jd] = gregorian_to_jalali($gy, $gm, $gd);
    return sprintf('%04d/%02d/%02d', $jy, $jm, $jd);
}

function jalaliToTimestamp(string $jalaliDate, bool $endOfDay = false): ?int
{
    if ($jalaliDate === '') {
        return null;
    }
    $normalized = toEnglishDigits(trim($jalaliDate));
    if (!preg_match('/^(\d{4})[-\/](\d{1,2})[-\/](\d{1,2})$/', $normalized, $matches)) {
        return null;
    }
    [$jy, $jm, $jd] = [(int)$matches[1], (int)$matches[2], (int)$matches[3]];
    if ($jm < 1 || $jm > 12 || $jd < 1 || $jd > 31) {
        return null;
    }
    [$gy, $gm, $gd] = jalali_to_gregorian($jy, $jm, $jd);
    if (!checkdate($gm, $gd, $gy)) {
        return null;
    }
    $time = $endOfDay ? '23:59:59' : '00:00:00';
    return strtotime(sprintf('%04d-%02d-%02d %s', $gy, $gm, $gd, $time));
}

function buildQueryString(array $state, array $overrides = []): string
{
    $merged = array_merge($state, $overrides);
    $filtered = [];
    foreach ($merged as $key => $value) {
        if ($value === null || $value === '') {
            continue;
        }
        $filtered[$key] = $value;
    }
    $query = http_build_query($filtered);
    return $query ? '?' . $query : '';
}

$sortOrder = strtolower($_GET['sort'] ?? 'new');
$sortOrder = in_array($sortOrder, ['new', 'old'], true) ? $sortOrder : 'new';

$currentCat = strtoupper($_GET['cat'] ?? 'ALL');
if (!array_key_exists($currentCat, $categoryMap)) {
    $currentCat = 'ALL';
}

$fromInputRaw = trim($_GET['from'] ?? '');
$toInputRaw   = trim($_GET['to'] ?? '');

$fromTimestamp = jalaliToTimestamp($fromInputRaw);
$toTimestamp   = jalaliToTimestamp($toInputRaw, true);

$imagesMeta = [];
foreach ($files as $file) {
    $info = pathinfo($file);
    $filename = $info['basename'];
    $extension = strtolower($info['extension'] ?? '');
    $mtime = filemtime($file) ?: time();
    $takenAt = $mtime;

    if (function_exists('exif_read_data') && in_array($extension, ['jpg', 'jpeg'], true)) {
        $exif = @exif_read_data($file, 'EXIF');
        if ($exif !== false) {
            $exifKeys = ['DateTimeOriginal', 'DateTimeDigitized', 'CreateDate', 'DateTime'];
            foreach ($exifKeys as $key) {
                if (!empty($exif[$key])) {
                    $candidate = strtotime($exif[$key]);
                    if ($candidate) {
                        $takenAt = $candidate;
                        break;
                    }
                }
            }
        }
    }

    $parts = explode('_', $filename);
    $prefix = strtoupper($parts[0] ?? '');
    $catKey = array_key_exists($prefix, $categoryMap) ? $prefix : 'OTHER';

    $imagesMeta[] = [
        'path'       => $file,
        'name'       => $filename,
        'cat_key'    => $catKey,
        'timestamp'  => $takenAt,
        'jalaliDate' => toPersianDigits(toJalaliString($takenAt)),
        'jalaliTime' => toPersianDigits(date('H:i', $takenAt)),
        'label'      => $categoryMap[$catKey] ?? 'سایر',
    ];
}

$filteredByDate = array_filter($imagesMeta, function ($item) use ($fromTimestamp, $toTimestamp) {
    if ($fromTimestamp && $item['timestamp'] < $fromTimestamp) {
        return false;
    }
    if ($toTimestamp && $item['timestamp'] > $toTimestamp) {
        return false;
    }
    return true;
});

$categoryCounts = array_fill_keys(array_keys($categoryMap), 0);
foreach ($filteredByDate as $item) {
    $categoryCounts['ALL']++;
    $categoryCounts[$item['cat_key']] = ($categoryCounts[$item['cat_key']] ?? 0) + 1;
}

$filteredImages = array_values(array_filter($filteredByDate, function ($item) use ($currentCat) {
    return $currentCat === 'ALL' ? true : $item['cat_key'] === $currentCat;
}));

usort($filteredImages, function ($a, $b) use ($sortOrder) {
    return $sortOrder === 'old'
        ? $a['timestamp'] <=> $b['timestamp']
        : $b['timestamp'] <=> $a['timestamp'];
});

$queryState = [
    'sort' => $sortOrder !== 'new' ? $sortOrder : null,
    'from' => $fromInputRaw ?: null,
    'to'   => $toInputRaw ?: null,
];

$fromDisplay = $fromInputRaw !== '' ? toPersianDigits(toEnglishDigits($fromInputRaw)) : '';
$toDisplay   = $toInputRaw !== '' ? toPersianDigits(toEnglishDigits($toInputRaw)) : '';
$resultCount = count($filteredImages);
?>
<!DOCTYPE html>
<html lang="fa">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>گالری تصاویر و مدیریت دوربین‌ها</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/persian-datepicker@1.2.0/dist/css/persian-datepicker.min.css">
<style>
/* دکمهٔ دسترسی به صفحهٔ تنظیمات */
.settings-link{
  display:flex;
  justify-content:center;
  align-items:center;
  padding:12px 18px;
  border-radius:16px;
  margin-top:10px;
  background:linear-gradient(135deg,#4cbaf2,#5ad6ff);
  color:#031128;
  font-weight:600;
  letter-spacing:-0.02em;
  box-shadow:0 18px 44px rgba(90,214,255,0.35);
  transition:transform 0.2s ease,box-shadow 0.2s ease;
}
.settings-link:hover{
  transform:translateY(-2px);
  box-shadow:0 24px 55px rgba(90,214,255,0.45);
}
</style>
</head>
<body class="gallery-bg">
<header class="app-header">
  <div class="header-wrap">
    <div class="app-logo">
      <span class="logo-spark">⚡</span>
      <div>
        <strong>پنل گالری</strong>
        <small>مدیریت تصاویر و دوربین‌ها</small>
      </div>
    </div>
    <div class="header-actions">
      <a href="logout.php">خروج</a>
    </div>
  </div>
</header>

<main class="layout">
  <section class="main-panel glass">
    <div class="panel-heading">
      <div>
        <h1>📸 گالری تصاویر</h1>
        <p>مرتب‌سازی و فیلتر بر اساس دسته‌بندی و تاریخ شمسی</p>
      </div>
      <span class="count-chip"><?php echo toPersianDigits($resultCount); ?> مورد</span>
    </div>

    <form class="filters glass-sub" method="get">
      <?php if ($currentCat !== 'ALL'): ?>
        <input type="hidden" name="cat" value="<?php echo htmlspecialchars($currentCat, ENT_QUOTES, 'UTF-8'); ?>">
      <?php endif; ?>
      <div class="filter-group">
        <label for="sort">مرتب‌سازی تاریخ</label>
        <select id="sort" name="sort">
          <option value="new" <?php echo $sortOrder === 'new' ? 'selected' : ''; ?>>جدیدترین </option>
          <option value="old" <?php echo $sortOrder === 'old' ? 'selected' : ''; ?>>قدیمی‌ترین </option>
        </select>
      </div>
      <div class="filter-group">
        <label for="fromDate">از تاریخ (شمسی)</label>
        <input type="text" id="fromDate" name="from" placeholder="مثلاً ۱۴۰۳/۰۱/۲۰" value="<?php echo htmlspecialchars($fromDisplay, ENT_QUOTES, 'UTF-8'); ?>">
      </div>
      <div class="filter-group">
        <label for="toDate">تا تاریخ (شمسی)</label>
        <input type="text" id="toDate" name="to" placeholder="مثلاً ۱۴۰۳/۰۲/۳۰" value="<?php echo htmlspecialchars($toDisplay, ENT_QUOTES, 'UTF-8'); ?>">
      </div>
      <div class="filter-actions">
        <button type="submit">اعمال فیلتر</button>
        <a class="reset" href="gallery.php">ریست</a>
      </div>
    </form>

    <?php if ($resultCount === 0): ?>
      <div class="empty">
        تصویری با فیلترهای فعلی یافت نشد. فیلترها را بازنشانی کنید یا تاریخ دیگری انتخاب نمایید.
      </div>
    <?php else: ?>
      <div class="gallery-grid">
        <?php foreach ($filteredImages as $image): ?>
          <div class="card">
            <div class="card-header">
              <span class="badge"><?php echo htmlspecialchars($image['label'], ENT_QUOTES, 'UTF-8'); ?></span>
              <span class="filename" title="<?php echo htmlspecialchars($image['name'], ENT_QUOTES, 'UTF-8'); ?>">
                <?php echo htmlspecialchars($image['name'], ENT_QUOTES, 'UTF-8'); ?>
              </span>
            </div>
            <a href="<?php echo htmlspecialchars($image['path'], ENT_QUOTES, 'UTF-8'); ?>"
               class="thumb"
               data-lightbox="gallery"
               data-title="<?php echo htmlspecialchars($image['name'], ENT_QUOTES, 'UTF-8'); ?>"
               data-meta="تاریخ: <?php echo htmlspecialchars($image['jalaliDate'], ENT_QUOTES, 'UTF-8'); ?> • ساعت: <?php echo htmlspecialchars($image['jalaliTime'], ENT_QUOTES, 'UTF-8'); ?>">
              <img src="<?php echo htmlspecialchars($image['path'], ENT_QUOTES, 'UTF-8'); ?>" alt="<?php echo htmlspecialchars($image['name'], ENT_QUOTES, 'UTF-8'); ?>">
            </a>
            <div class="card-footer">
              <span class="datetime">تاریخ: <?php echo htmlspecialchars($image['jalaliDate'], ENT_QUOTES, 'UTF-8'); ?></span>
              <span class="time">ساعت: <?php echo htmlspecialchars($image['jalaliTime'], ENT_QUOTES, 'UTF-8'); ?></span>
            </div>
          </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </section>

  <aside class="sidebar glass">
    <h3>دسته‌بندی‌ها</h3>
    <ul class="cat-list">
      <?php foreach ($categoryMap as $catKey => $label): ?>
        <?php
          $isActive = $catKey === ($currentCat === 'ALL' ? 'ALL' : $currentCat);
          $count = toPersianDigits($categoryCounts[$catKey] ?? 0);
          $query = buildQueryString($queryState, ['cat' => $catKey === 'ALL' ? null : $catKey]);
        ?>
        <li class="<?php echo $isActive ? 'active' : ''; ?>">
          <a href="gallery.php<?php echo $query; ?>">
            <span><?php echo htmlspecialchars($label, ENT_QUOTES, 'UTF-8'); ?></span>
            <span><?php echo $count; ?></span>
          </a>
        </li>
      <?php endforeach; ?>
    </ul>
    <p class="hint">
      با انتخاب دسته، مرتب‌سازی تاریخ و تعیین بازهٔ زمانی شمسی می‌توانید تصاویر را دقیق‌تر مدیریت کنید. برای بازگردانی همهٔ نتایج، روی «ریست» کلیک کنید.
    </p>

    <hr style="opacity:0.3; margin: 12px 0;">

    <h3>تنظیمات دوربین‌ها</h3>
    <p class="hint">
      برای تنظیم بازهٔ زمانی، کیفیت JPEG، اندازهٔ فریم و وضعیت کپچر هر دوربین، از صفحهٔ اختصاصی استفاده کنید.
    </p>
    <a class="settings-link" href="camera_settings.php">
      مدیریت کامل دوربین‌ها
    </a>
  </aside>
</main>

<div id="lightbox">
  <div class="lightbox-inner">
    <div class="lightbox-frame">
      <div class="lightbox-header">
        <span id="lightbox-title"></span>
        <button type="button" class="lightbox-close" aria-label="بستن">×</button>
      </div>
      <div class="lightbox-body">
        <img src="" alt="">
      </div>
      <div class="lightbox-footer">
        <small id="lightbox-meta"></small>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/persian-date@1.1.0/dist/persian-date.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/persian-datepicker@1.2.0/dist/js/persian-datepicker.min.js"></script>
<script>
$(function () {
  var baseOptions = {
    initialValue: false,
    format: 'YYYY/MM/DD',
    calendarType: 'persian',
    calendar: {
      persian: { locale: 'fa', leapYearMode: 'astronomical' }
    },
    navigator: { enabled: true },
    toolbox: {
      calendarSwitch: { enabled: false },
      todayButton: { enabled: true },
      submitButton: { enabled: false }
    },
    autoClose: true,
    responsive: true
  };
  $('#fromDate').persianDatepicker($.extend(true, {}, baseOptions));
  $('#toDate').persianDatepicker($.extend(true, {}, baseOptions));
});
</script>
<script>
document.addEventListener('DOMContentLoaded', function () {
  var lightbox = document.getElementById('lightbox');
  if (!lightbox) { return; }
  var lightboxImg = lightbox.querySelector('.lightbox-body img');
  var lightboxTitle = document.getElementById('lightbox-title');
  var lightboxMeta = document.getElementById('lightbox-meta');
  var closeBtn = lightbox.querySelector('.lightbox-close');

  function closeLightbox() {
    lightbox.classList.remove('active');
    lightboxImg.src = '';
    lightboxTitle.textContent = '';
    lightboxMeta.textContent = '';
  }

  document.querySelectorAll('[data-lightbox]').forEach(function (item) {
    item.addEventListener('click', function (event) {
      event.preventDefault();
      lightboxImg.src = item.getAttribute('href');
      lightboxImg.alt = item.dataset.title || '';
      lightboxTitle.textContent = item.dataset.title || '';
      lightboxMeta.textContent = item.dataset.meta || '';
      lightbox.classList.add('active');
    });
  });

  closeBtn.addEventListener('click', closeLightbox);
  lightbox.addEventListener('click', function (event) {
    if (event.target === lightbox) {
      closeLightbox();
    }
  });
  document.addEventListener('keydown', function (event) {
    if (event.key === 'Escape') {
      closeLightbox();
    }
  });
});
</script>
</body>
</html>
