<?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];

// --- 1. معالجة الإضافة والتعديل (POST) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    $id = $_POST['testimonial_id'];
    $student_name = $_POST['student_name'];
    $country_ar = $_POST['country_ar'];
    $country_tr = $_POST['country_tr'];
    $country_en = $_POST['country_en'];
    $content_ar = $_POST['content_ar'];
    $content_tr = $_POST['content_tr'];
    $content_en = $_POST['content_en'];
    $stars = (int)$_POST['stars'];

    if (!empty($id)) {
        // تحديث
        $stmt = $conn->prepare("UPDATE testimonials SET student_name=?, country_ar=?, country_tr=?, country_en=?, content_ar=?, content_tr=?, content_en=?, stars=? WHERE id=?");
        $stmt->bind_param("sssssssii", $student_name, $country_ar, $country_tr, $country_en, $content_ar, $content_tr, $content_en, $stars, $id);
        $msg = "updated";
    } else {
        // إضافة جديد
        $stmt = $conn->prepare("INSERT INTO testimonials (student_name, country_ar, country_tr, country_en, content_ar, content_tr, content_en, stars) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("sssssssi", $student_name, $country_ar, $country_tr, $country_en, $content_ar, $content_tr, $content_en, $stars);
        $msg = "added";
    }
    $stmt->execute();
    header("Location: testimonials.php?msg=" . $msg);
    exit();
}

// --- 2. معالجة الحذف (GET) ---
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $conn->query("DELETE FROM testimonials WHERE id = $id");
    header("Location: testimonials.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['testimonials']; ?> | <?php echo $t['institute_name']; ?></title>
    <style>
        :root {
            --primary-gold: #d4af37;
            --charcoal: #2d3436;
            --bg-cream: #fcf5e5; 
            --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 Style --- */
        .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;
            font-weight: 500; text-decoration: none; display: block;
        }
        .nav-link:hover, .nav-link.active { background: var(--primary-gold); color: #1a1a1a !important; font-weight: bold; }

        .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; }
        .star-gold { color: #f1c40f; font-size: 0.85rem; }

        .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; }

        /* --- تظبيط المودال (التصميم الجديد) --- */
        .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; }
    </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">
        <?php $current_page = basename($_SERVER['PHP_SELF']); ?>
        <a class="nav-link <?php echo $current_page == 'index.php' ? 'active' : ''; ?>" href="index.php"><i class="fas fa-th-large mx-2"></i> <?php echo $t['dashboard']; ?></a>
        <a class="nav-link <?php echo $current_page == 'courses.php' ? 'active' : ''; ?>" href="courses.php"><i class="fas fa-book-open mx-2"></i> <?php echo $t['courses']; ?></a>
        <a class="nav-link <?php echo $current_page == 'slider.php' ? 'active' : ''; ?>" href="slider.php"><i class="fas fa-images mx-2"></i> <?php echo $t['slider']; ?></a>
        <a class="nav-link <?php echo $current_page == 'testimonials.php' ? 'active' : ''; ?>" href="testimonials.php"><i class="fas fa-comment-dots mx-2"></i> <?php echo $t['testimonials']; ?></a>
        <a class="nav-link <?php echo $current_page == 'gallery.php' ? 'active' : ''; ?>" href="gallery.php"><i class="fas fa-photo-video mx-2"></i> <?php echo $t['gallery']; ?></a>
        <a class="nav-link <?php echo $current_page == 'subscribers.php' ? 'active' : ''; ?>" 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 echo $t['msg_'.$_GET['msg']] ?? $_GET['msg']; ?>
            <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-comment-dots me-2"></i> <?php echo $t['testimonials']; ?></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_story']; ?>
            </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['student_name']; ?></th>
                        <th><?php echo $t['country']; ?></th>
                        <th><?php echo $t['rating']; ?></th>
                        <th><?php echo $t['action']; ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $result = $conn->query("SELECT * FROM testimonials ORDER BY id DESC");
                    while($row = $result->fetch_assoc()):
                    ?>
                    <tr>
                       <td>
    <div class="fw-bold"><?php echo $row['student_name']; ?></div>
</td>
                        <td><span class="badge rounded-pill bg-light text-dark border"><?php echo $row['country_'.$lang]; ?></span></td>
                        <td class="star-gold">
                            <?php for($i=1;$i<=5;$i++) echo ($i<=$row['stars']?'<i class="fas fa-star"></i>':'<i class="far fa-star text-muted"></i>'); ?>
                        </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="testimonialModal" 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">
                <div class="modal-body p-4">
                    <input type="hidden" name="action" value="save">
                    <input type="hidden" name="testimonial_id" id="modal_id">
                    
                    <div class="row g-3 mb-4">
                        <div class="col-md-8">
                            <label class="small fw-bold text-muted mb-1"><?php echo $t['student_name']; ?></label>
                            <input type="text" name="student_name" id="modal_name" class="form-control" required>
                        </div>
                        <div class="col-md-4">
                            <label class="small fw-bold text-muted mb-1"><?php echo $t['rating']; ?></label>
                            <select name="stars" id="modal_stars" class="form-select">
                                <option value="5">⭐⭐⭐⭐⭐</option>
                                <option value="4">⭐⭐⭐⭐</option>
                                <option value="3">⭐⭐⭐</option>
                                <option value="2">⭐⭐</option>
                                <option value="1">⭐</option>
                            </select>
                        </div>
                    </div>

                    <div class="lang-section-custom">
<span class="badge-lang bg-dark text-white"><?php echo $t['arabic']; ?></span>
                        <input type="text" name="country_ar" id="modal_c_ar" class="form-control mb-2" placeholder="<?php echo $t['country']; ?>" dir="rtl" required>
                        <textarea name="content_ar" id="modal_t_ar" class="form-control" rows="2" placeholder="<?php echo $t['review_text']; ?>" dir="rtl" required></textarea>
                    </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="country_tr" id="modal_c_tr" class="form-control mb-2" placeholder="Ülke" required>
                        <textarea name="content_tr" id="modal_t_tr" class="form-control" rows="2" placeholder="Yorum" required></textarea>
                    </div>

                    <div class="lang-section-custom" style="border-color: #0984e3;">
                        <span class="badge-lang bg-primary text-white">English</span>
                        <input type="text" name="country_en" id="modal_c_en" class="form-control mb-2" placeholder="Country" required>
                        <textarea name="content_en" id="modal_t_en" class="form-control" rows="2" placeholder="Review content" required></textarea>
                    </div>

                    <button type="submit" class="btn btn-gold w-100 py-3 mt-3 rounded-3 shadow-sm" id="modalBtn"></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('testimonialModal'));

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

function openModal(mode, data = null) {
    document.getElementById('modal_id').value = '';
    const fields = ['name', 'stars', 'c_ar', 'c_tr', 'c_en', 't_ar', 't_tr', 't_en'];
    fields.forEach(f => {
        const el = document.getElementById('modal_'+f);
        if(el) el.value = (f === 'stars' ? '5' : '');
    });

    if (mode === 'add') {
        document.getElementById('modalTitle').innerText = "<?php echo $t['add_story']; ?>";
        document.getElementById('modalBtn').innerText = "<?php echo $t['save']; ?>";
    } else {
        document.getElementById('modalTitle').innerText = "<?php echo $t['edit_story']; ?>";
        document.getElementById('modalBtn').innerText = "<?php echo $t['update_data']; ?>";
        document.getElementById('modal_id').value = data.id;
        document.getElementById('modal_name').value = data.student_name;
        document.getElementById('modal_stars').value = data.stars;
        document.getElementById('modal_c_ar').value = data.country_ar;
        document.getElementById('modal_c_tr').value = data.country_tr;
        document.getElementById('modal_c_en').value = data.country_en;
        document.getElementById('modal_t_ar').value = data.content_ar;
        document.getElementById('modal_t_tr').value = data.content_tr;
        document.getElementById('modal_t_en').value = data.content_en;
    }
    myModal.show();
}

// مسح رسالة النجاح من الرابط بعد العرض
if (window.history.replaceState) {
    const url = new URL(window.location.href);
    if (url.searchParams.has('msg')) {
        url.searchParams.delete('msg');
        window.history.replaceState({path: url.href}, '', url.href);
    }
}
setTimeout(function() {
    let alertElement = document.getElementById('msg-alert');
    if (alertElement) {
        let bsAlert = new bootstrap.Alert(alertElement);
        bsAlert.close();
    }
}, 3000); // 3000 ملي ثانية تعني 3 ثواني
</script>
</body>
</html>