<?php
include '../includes/db.php';
include '../includes/auth.php'; // session check
 include 'header.php'; 
$success = '';
$error = '';

// DELETE slide
if(isset($_GET['delete'])){
    $id = (int)$_GET['delete'];
    $slide = $conn->query("SELECT file_path FROM slider WHERE id=$id")->fetch_assoc();
    if($slide && file_exists('../'.$slide['file_path'])) unlink('../'.$slide['file_path']);
    $conn->query("DELETE FROM slider WHERE id=$id");
    header("Location: Slider.php");
    exit;
}

// EDIT slide
$editing = false;
if(isset($_GET['edit'])){
    $id = (int)$_GET['edit'];
    $slide = $conn->query("SELECT * FROM slider WHERE id=$id")->fetch_assoc();
    if(!$slide) die("Slide not found");
    $editing = true;

    if($_SERVER['REQUEST_METHOD'] === 'POST'){
        $type = $_POST['type'];
        $title = $conn->real_escape_string($_POST['title']);
        $caption = $conn->real_escape_string($_POST['caption']);
        $position = $_POST['position'];

        // Update file if new file uploaded
        $file_path_db = $slide['file_path'];
        if(isset($_FILES['file']) && $_FILES['file']['error']==0){
            $target_dir = "../assets/img/";
            if(!is_dir($target_dir)) mkdir($target_dir,0755,true);
            $target_file = $target_dir . basename($_FILES["file"]["name"]);
            if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)){
                if(file_exists('../'.$slide['file_path'])) unlink('../'.$slide['file_path']); // remove old
                $file_path_db = "assets/img/".basename($_FILES["file"]["name"]);
            }
        }

        $conn->query("UPDATE slider SET type='$type', file_path='$file_path_db', title='$title', caption='$caption', position='$position' WHERE id=$id");
        $success = "Slide updated successfully!";
    }
}

// ADD new slide
if($_SERVER['REQUEST_METHOD'] === 'POST' && !$editing){
    $type = $_POST['type'];
    $title = $conn->real_escape_string($_POST['title']);
    $caption = $conn->real_escape_string($_POST['caption']);
    $position = $_POST['position'];

    $file_path_db = '';
    if(isset($_FILES['file']) && $_FILES['file']['error']==0){
        $target_dir = "../assets/img/";
        if(!is_dir($target_dir)) mkdir($target_dir,0755,true);
        $target_file = $target_dir . basename($_FILES["file"]["name"]);
        if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)){
            $file_path_db = "assets/img/".basename($_FILES["file"]["name"]);
        }
    }

    $conn->query("INSERT INTO slider (type, file_path, title, caption, position) VALUES ('$type','$file_path_db','$title','$caption','$position')");
    $success = "Slide added successfully!";
}
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= $editing ? "Edit Slide" : "Add New Slide" ?></title>

<script src="https://cdn.jsdelivr.net/npm/tinymce@6/tinymce.min.js"></script>
<script>
tinymce.init({
    selector:'#caption',
    height:300,
    plugins:'advlist autolink lists link image charmap preview anchor searchreplace code fullscreen insertdatetime media table help wordcount',
    toolbar:'undo redo | blocks | bold italic underline | alignleft aligncenter alignright | bullist numlist | link image media | removeformat | code',
    setup:(editor)=>{editor.on('change',()=>editor.save());}
});
</script>

<style>
body{font-family:'Vazir',sans-serif;background:#f4f7fb;color:#333;margin:0;padding:0;}
h2{text-align:center;color:#1a237e;margin-top:30px;font-size:28px;}
form{background:#fff;max-width:900px;margin:30px auto;padding:40px 50px;border-radius:20px;box-shadow:0 8px 20px rgba(0,0,0,0.1);direction:rtl;}
label{font-weight:bold;color:#1a237e;display:block;margin-bottom:8px;}
input[type="text"], input[type="file"], textarea, input[type="number"]{width:100%;padding:10px 15px;margin-bottom:20px;border:1px solid #ccd1e4;border-radius:10px;font-size:15px;transition:0.2s;}
input:focus, textarea:focus{border-color:#1a73e8;box-shadow:0 0 5px rgba(26,115,232,0.3);outline:none;}
button{background:linear-gradient(90deg,#1a73e8,#0c47b7);color:#fff;border:none;padding:14px 35px;border-radius:30px;font-size:16px;cursor:pointer;transition:0.3s;}
button:hover{background:linear-gradient(90deg,#0c47b7,#1a237e);}
.alert{max-width:900px;margin:20px auto;padding:15px 25px;border-radius:10px;text-align:center;font-weight:bold;}
.alert.success{background:#d7ffd9;color:#1b5e20;border:1px solid #81c784;}
.alert.error{background:#ffe0e0;color:#b71c1c;border:1px solid #ef9a9a;}
img{display:block;margin-top:10px;border-radius:15px;max-width:250px;box-shadow:0 4px 10px rgba(0,0,0,0.15);}
table{width:90%;max-width:900px;margin:30px auto;border-collapse:collapse;}
table th, table td{border:1px solid #ccc;padding:10px;text-align:center;}
table th{background:#1a237e;color:#fff;}
a.edit,a.delete{padding:5px 12px;border-radius:6px;color:#fff;text-decoration:none;margin:0 5px;}
a.edit{background:#28a745;} a.edit:hover{background:#1e7e34;}
a.delete{background:#dc3545;} a.delete:hover{background:#a71d2a;}
</style>
</head>
<body>

<h2><?= $editing ? "Edit Slide" : "Add New Slide" ?></h2>

<?php if($success): ?>
<div class="alert success"><?= $success ?></div>
<?php endif; ?>
<?php if($error): ?>
<div class="alert error"><?= $error ?></div>
<?php endif; ?>

<form method="post" enctype="multipart/form-data">
<label>Type:</label>
<select name="type">
    <option value="image" <?= $editing && $slide['type']=='image'?'selected':'' ?>>Image</option>
    <option value="video" <?= $editing && $slide['type']=='video'?'selected':'' ?>>Video</option>
</select>

<label>Title:</label>
<input type="text" name="title" value="<?= $editing ? htmlspecialchars($slide['title']) : '' ?>" required>

<label>Caption:</label>
<textarea id="caption" name="caption"><?= $editing ? htmlspecialchars($slide['caption']) : '' ?></textarea>

<label>Position:</label>
<input type="number" name="position" value="<?= $editing ? $slide['position'] : 1 ?>" required>

<label>File:</label>
<input type="file" name="file">
<?php if($editing && $slide['file_path']): ?>
    <?php if($slide['type']=='image'): ?>
        <img src="../<?= $slide['file_path'] ?>" alt="Slide Image">
    <?php else: ?>
        <video src="../<?= $slide['file_path'] ?>" controls style="max-width:250px;margin-top:10px;"></video>
    <?php endif; ?>
<?php endif; ?>

<button type="submit"><?= $editing ? "Update Slide" : "Add Slide" ?></button>
</form>

<!-- Existing slides -->
<table>
<thead>
<tr>
<th>ID</th>
<th>Type</th>
<th>Title</th>
<th>Position</th>
<th>File</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
$slides = $conn->query("SELECT * FROM slider ORDER BY position ASC");
while($s = $slides->fetch_assoc()):
?>
<tr>
<td><?= $s['id'] ?></td>
<td><?= $s['type'] ?></td>
<td><?= htmlspecialchars($s['title']) ?></td>
<td><?= $s['position'] ?></td>
<td>
<?php if($s['type']=='image'): ?>
<img src="../<?= $s['file_path'] ?>" alt="Slide" style="width:80px;height:50px;object-fit:cover;border-radius:5px;">
<?php else: ?>
<video src="../<?= $s['file_path'] ?>" style="width:80px;height:50px;" controls></video>
<?php endif; ?>
</td>
<td>
<a href="Slider.php?edit=<?= $s['id'] ?>" class="edit">Edit</a>
<a href="Slider.php?delete=<?= $s['id'] ?>" class="delete" onclick="return confirm('Delete this slide?')">Delete</a>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>

</body>
</html>
