<?php
session_start();
if (!isset($_SESSION['admin_id'])) { header("Location: login.php"); exit(); }
include 'db_connection.php';
include 'admin_lang.php'; 

// منطق اللغة
if (isset($_GET['lang'])) { $_SESSION['lang'] = $_GET['lang']; }
$lang = isset($_SESSION['lang']) ? $_SESSION['lang'] : 'ar';
$t = $translations[$lang];

// معالجة الرفع (إضافة وتعديل)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    $t_ar = $_POST['title_ar'];
    $t_tr = $_POST['title_tr'];
    $t_en = $_POST['title_en'];
    $gallery_id = $_POST['gallery_id'];

    if (!empty($_FILES['image']['name'])) {
        $img_name = time() . "_" . $_FILES['image']['name'];
        move_uploaded_file($_FILES['image']['tmp_name'], "uploads/" . $img_name);
        
        if (!empty($gallery_id)) {
            $stmt = $conn->prepare("UPDATE gallery SET image_path=?, title_ar=?, title_tr=?, title_en=? WHERE id=?");
            $stmt->bind_param("ssssi", $img_name, $t_ar, $t_tr, $t_en, $gallery_id);
            $msg = "updated";
        } else {
            $stmt = $conn->prepare("INSERT INTO gallery (image_path, title_ar, title_tr, title_en) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("ssss", $img_name, $t_ar, $t_tr, $t_en);
            $msg = "added";
        }
    } else {
        if (!empty($gallery_id)) {
            $stmt = $conn->prepare("UPDATE gallery SET title_ar=?, title_tr=?, title_en=? WHERE id=?");
            $stmt->bind_param("sssi", $t_ar, $t_tr, $t_en, $gallery_id);
            $msg = "updated";
        }
    }
    $stmt->execute();
    header("Location: gallery.php?msg=" . $msg);
    exit();
}

// معالجة الحذف
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $res = $conn->query("SELECT image_path FROM gallery WHERE id = $id");
    $img = $res->fetch_assoc();
    if($img) @unlink("uploads/" . $img['image_path']);
    $conn->query("DELETE FROM gallery WHERE id = $id");
    header("Location: gallery.php?msg=deleted");
    exit();
}
?>

<!DOCTYPE html>
<html lang="<?php echo $lang; ?>" dir="<?php echo $t['dir']; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;600;700;800&display=swap" rel="stylesheet">
    <title><?php echo $t['gallery']; ?> | <?php echo $t['institute_name']; ?></title>
    <style>
        :root {
            --primary-gold: #d4af37;
            --charcoal: #2d3436;
            --sidebar-width: 280px;
        }

        body { 
            font-family: 'Cairo', sans-serif; 
            background: linear-gradient(rgba(252, 245, 229, 0.9), rgba(252, 245, 229, 0.9)), url('../pngegg2.jpg') fixed; 
            background-size: cover; color: #333; margin: 0; overflow-x: hidden;
        }

        /* --- Sidebar & Layout --- */
        .sidebar { 
            width: var(--sidebar-width); height: 100vh; 
            background: linear-gradient(180deg, var(--charcoal), #1a1a1a); 
            border-<?php echo ($t['dir'] == 'rtl' ? 'left' : 'right'); ?>: 3px solid var(--primary-gold);
            position: fixed; top: 0; <?php echo ($t['dir'] == 'rtl' ? 'right' : 'left'); ?>: 0; 
            z-index: 2000; transition: all 0.3s ease;
        }
        
        .main-content { 
            margin-<?php echo ($t['dir'] == 'rtl' ? 'right' : 'left'); ?>: var(--sidebar-width); 
            padding: 40px; min-height: 100vh; transition: 0.3s;
        }

        @media (max-width: 992px) {
            .sidebar { transform: translateX(<?php echo ($t['dir'] == 'rtl' ? '100%' : '-100%'); ?>); }
            .sidebar.active { transform: translateX(0); }
            .main-content { margin: 0 !important; padding: 15px; padding-top: 80px; }
            .mobile-header { display: flex !important; }
        }

        .mobile-header {
            display: none; position: fixed; top: 0; width: 100%; height: 65px;
            background: var(--charcoal); z-index: 1040; align-items: center; 
            justify-content: space-between; padding: 0 20px; border-bottom: 2px solid var(--primary-gold);
        }

        .nav-link { 
            color: rgba(255,255,255,0.7); margin: 5px 15px; border-radius: 10px; 
            transition: 0.3s; padding: 10px 15px; text-decoration: none; display: block;
        }
        .nav-link:hover, .nav-link.active { background: var(--primary-gold); color: #1a1a1a !important; font-weight: bold; }

        /* --- Cards & Tables --- */
        .card-custom { background: white; border-radius: 15px; border: none; box-shadow: 0 5px 20px rgba(0,0,0,0.05); overflow: hidden; }
        .card-header-gold { background: var(--charcoal); color: var(--primary-gold); padding: 15px 20px; display: flex; justify-content: space-between; align-items: center; }
        .btn-gold { background: var(--primary-gold); color: #1a1a1a; font-weight: bold; border: none; transition: 0.3s; }
        .btn-gold:hover { background: #b8962d; color: white; }
        
        .gallery-thumb { width: 80px; height: 55px; object-fit: cover; border-radius: 8px; border: 1px solid var(--primary-gold); }

        /* --- Modal Styling --- */
        .modal-content { border-radius: 15px; border: none; overflow: hidden; }
        .modal-header-custom {
            background: var(--charcoal); color: var(--primary-gold);
            padding: 18px 25px; display: flex; justify-content: space-between;
            align-items: center; border-bottom: 2px solid var(--primary-gold);
        }
        .btn-close-x { background: none; border: none; color: #888; font-size: 1.4rem; cursor: pointer; transition: 0.3s; }
        .btn-close-x:hover { color: var(--primary-gold); transform: rotate(90deg); }
        
        .lang-section-custom {
            padding: 15px; margin-bottom: 15px; background: #fcfcfc;
            border-radius: 12px; border: 1px solid #eee;
            border-<?php echo ($t['dir'] == 'rtl' ? 'right' : 'left'); ?>: 5px solid var(--primary-gold);
        }
        .badge-lang { font-size: 10px; padding: 5px 10px; margin-bottom: 10px; display: inline-block; border-radius: 4px; }
        
        .lang-link { color: #fff; text-decoration: none; font-size: 13px; opacity: 0.6; }
        .lang-link.active { opacity: 1; color: var(--primary-gold); font-weight: bold; }
    </style>
</head>
<body>

<div class="mobile-header shadow">
    <h6 class="mb-0 fw-bold text-white"><?php echo $t['institute_name']; ?></h6>
    <button class="btn text-warning" onclick="toggleSidebar()"><i class="fas fa-bars fa-lg"></i></button>
</div>

<div class="sidebar shadow" id="sidebar">
    <div class="d-lg-none text-<?php echo ($t['dir'] == 'rtl' ? 'start' : 'end'); ?> p-3">
        <button class="btn text-white" onclick="toggleSidebar()"><i class="fas fa-times fa-lg"></i></button>
    </div>

    <div class="text-center my-3">
        <img src="../logo.png" alt="Logo" style="max-height: 60px;">
        <h6 class="fw-bold mt-2 text-white px-2"><?php echo $t['institute_name']; ?></h6>
        <div class="mt-2 small">
            <a href="?lang=ar" class="lang-link <?php echo $lang=='ar'?'active':''; ?>">AR</a> |
            <a href="?lang=tr" class="lang-link <?php echo $lang=='tr'?'active':''; ?>">TR</a> |
            <a href="?lang=en" class="lang-link <?php echo $lang=='en'?'active':''; ?>">EN</a>
        </div>
    </div>
    
    <nav class="nav flex-column">
        <a class="nav-link" href="index.php"><i class="fas fa-th-large mx-2"></i> <?php echo $t['dashboard']; ?></a>
        <a class="nav-link" href="courses.php"><i class="fas fa-book-open mx-2"></i> <?php echo $t['courses']; ?></a>
        <a class="nav-link" href="slider.php"><i class="fas fa-images mx-2"></i> <?php echo $t['slider']; ?></a>
        <a class="nav-link" href="testimonials.php"><i class="fas fa-comment-dots mx-2"></i> <?php echo $t['testimonials']; ?></a>
        <a class="nav-link active" href="gallery.php"><i class="fas fa-photo-video mx-2"></i> <?php echo $t['gallery']; ?></a>
        <a class="nav-link" href="subscribers.php"><i class="fas fa-envelope-open-text mx-2"></i> <?php echo $t['subscribers']; ?></a>
        <hr class="mx-3 my-2" style="color: rgba(255,255,255,0.2);">
        <a class="nav-link text-danger fw-bold" href="logout.php"><i class="fas fa-power-off mx-2"></i> <?php echo $t['logout']; ?></a>
    </nav>
</div>

<div class="main-content">
    <?php if(isset($_GET['msg'])): ?>
        <div class="alert alert-info alert-dismissible fade show shadow-sm border-0 rounded-3 mb-4" role="alert" id="msg-alert">
            <i class="fas fa-info-circle me-2"></i> 
            <?php 
                $m = $_GET['msg'];
                echo ($m == 'added' ? $t['msg_added'] : ($m == 'updated' ? $t['msg_updated'] : $t['msg_deleted'])); 
            ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="card-custom shadow-sm">
        <div class="card-header-gold">
            <h6 class="mb-0 fw-bold"><i class="fas fa-images me-2"></i> <?php echo $t['gallery']; ?></h6>
            <button class="btn btn-gold btn-sm px-4 rounded-pill shadow-sm" onclick="openModal('add')">
                <i class="fas fa-plus me-1"></i> <?php echo $t['add_img'] ?? 'إضافة صورة'; ?>
            </button>
        </div>
        
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0 text-center">
                <thead>
                    <tr class="small text-muted text-uppercase">
                        <th><?php echo $t['image']; ?></th>
                        <th class="text-<?php echo ($t['dir'] == 'rtl' ? 'right' : 'left'); ?>"><?php echo $t['title']; ?></th>
                        <th><?php echo $t['action']; ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $result = $conn->query("SELECT * FROM gallery ORDER BY id DESC");
                    while($row = $result->fetch_assoc()):
                    ?>
                    <tr>
                        <td style="width: 120px;"><img src="uploads/<?php echo $row['image_path']; ?>" class="gallery-thumb shadow-sm"></td>
                        <td class="text-<?php echo ($t['dir'] == 'rtl' ? 'right' : 'left'); ?>">
                            <div class="fw-bold"><?php echo $row['title_'.$lang]; ?></div>
                        </td>
                        <td>
                            <div class="btn-group">
                                <button class="btn btn-sm text-warning" onclick='openModal("edit", <?php echo json_encode($row, JSON_HEX_APOS); ?>)'><i class="fas fa-edit fa-lg"></i></button>
                                <a href="?delete=<?php echo $row['id']; ?>" class="btn btn-sm text-danger" onclick="return confirm('<?php echo $t['confirm_delete']; ?>')"><i class="fas fa-trash fa-lg"></i></a>
                            </div>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="galleryModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content shadow-lg">
            <div class="modal-header-custom">
                <h6 class="mb-0 fw-bold" id="modalTitle"></h6>
                <button type="button" class="btn-close-x" data-bs-dismiss="modal"><i class="fas fa-times"></i></button>
            </div>
            <form method="POST" enctype="multipart/form-data">
                <div class="modal-body p-4">
                    <input type="hidden" name="action" value="save">
                    <input type="hidden" name="gallery_id" id="modal_id">
                    
                    <div class="mb-4 text-center bg-light p-3 rounded-3 border">
                        <label class="small fw-bold text-muted mb-2 d-block"><?php echo $t['image']; ?></label>
                        <div id="current_img_display" class="mb-3"></div>
                        <input type="file" name="image" id="modal_image" class="form-control">
                        <small class="text-muted mt-1 d-block italic"><?php echo $t['leave_blank'] ?? 'اتركه فارغاً للإبقاء على الصورة الحالية'; ?></small>
                    </div>

                    <div class="lang-section-custom">
                        <span class="badge-lang bg-dark text-white"><?php echo $t['arabic']; ?></span>
                        <input type="text" name="title_ar" id="modal_title_ar" class="form-control" placeholder="عنوان الصورة بالعربية" dir="rtl" required>
                    </div>

                    <div class="lang-section-custom" style="border-color: #d63031;">
                        <span class="badge-lang bg-danger text-white">Türkçe</span>
                        <input type="text" name="title_tr" id="modal_title_tr" class="form-control" placeholder="Fotoğraf Başlığı" dir="ltr" required>
                    </div>

                    <div class="lang-section-custom" style="border-color: #0984e3;">
                        <span class="badge-lang bg-primary text-white">English</span>
                        <input type="text" name="title_en" id="modal_title_en" class="form-control" placeholder="Photo Title" dir="ltr" required>
                    </div>

                    <button type="submit" class="btn btn-gold w-100 py-3 mt-3 rounded-3 shadow-sm" id="modalBtn"><?php echo $t['save_gallery'] ?? 'حفظ في المعرض'; ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
const myModal = new bootstrap.Modal(document.getElementById('galleryModal'));

function toggleSidebar() {
    document.getElementById('sidebar').classList.toggle('active');
}

function openModal(mode, data = null) {
    document.getElementById('modal_id').value = '';
    document.getElementById('current_img_display').innerHTML = '';
    ['ar', 'tr', 'en'].forEach(l => document.getElementById('modal_title_'+l).value = '');

    if (mode === 'add') {
        document.getElementById('modalTitle').innerText = "<?php echo $t['add_img'] ?? 'إضافة صورة'; ?>";
        document.getElementById('modal_image').required = true;
        document.getElementById('modalBtn').innerText = "<?php echo $t['save_gallery'] ?? 'إضافة للمعرض'; ?>";
    } else {
        document.getElementById('modalTitle').innerText = "<?php echo $t['edit_gallery'] ?? 'تعديل الصورة'; ?>";
        document.getElementById('modal_id').value = data.id;
        document.getElementById('modalBtn').innerText = "<?php echo $t['update_data'] ?? 'تعديل البيانات'; ?>";
        
        ['ar', 'tr', 'en'].forEach(l => {
            document.getElementById('modal_title_'+l).value = data['title_'+l];
        });

        if(data.image_path) {
            document.getElementById('current_img_display').innerHTML = `<img src="uploads/${data.image_path}" class="gallery-thumb mb-2" style="width:150px; height:100px;">`;
        }
        document.getElementById('modal_image').required = false;
    }
    myModal.show();
}

// إخفاء التنبيه تلقائياً
setTimeout(function() {
    let alertElement = document.getElementById('msg-alert');
    if (alertElement) {
        let bsAlert = new bootstrap.Alert(alertElement);
        bsAlert.close();
    }
}, 3000);
</script>
</body>
</html>