<?php
include "db.php";

$uploadDir = "../uploads/";

/* ================= IMAGE FUNCTIONS ================= */

/* BACKGROUND IMAGE (must be 1920x700) */
function uploadBgImage($file, $uploadDir) {
    $tmp = $file['tmp_name'];

    $info = getimagesize($tmp);
    if ($info === false) {
        die("Invalid image");
    }

    [$w, $h, $type] = $info;

    if ($w != 1920 || $h != 700) {
        die("Background image must be exactly 1920 x 700");
    }

    $ext  = image_type_to_extension($type, false);
    $name = time() . "_bg_" . pathinfo($file['name'], PATHINFO_FILENAME) . "." . $ext;
    $path = $uploadDir . $name;

    $newImg = imagecreatetruecolor(1920, 700);

    switch ($type) {
        case IMAGETYPE_JPEG:
            $src = imagecreatefromjpeg($tmp);
            imagecopyresampled($newImg, $src, 0, 0, 0, 0, 1920, 700, $w, $h);
            imagejpeg($newImg, $path, 70);
            break;

        case IMAGETYPE_PNG:
            $src = imagecreatefrompng($tmp);
            imagealphablending($newImg, false);
            imagesavealpha($newImg, true);
            imagecopyresampled($newImg, $src, 0, 0, 0, 0, 1920, 700, $w, $h);
            imagepng($newImg, $path, 6);
            break;

        case IMAGETYPE_GIF:
            $src = imagecreatefromgif($tmp);
            imagecopyresampled($newImg, $src, 0, 0, 0, 0, 1920, 700, $w, $h);
            imagegif($newImg, $path);
            break;

        case IMAGETYPE_WEBP:
            $src = imagecreatefromwebp($tmp);
            imagecopyresampled($newImg, $src, 0, 0, 0, 0, 1920, 700, $w, $h);
            imagewebp($newImg, $path, 70);
            break;

        default:
            die("Unsupported image format");
    }

    imagedestroy($src);
    imagedestroy($newImg);

    return $name;
}


/* FRONT IMAGE (any size, only compress) */
function uploadFrontImage($file, $uploadDir) {
    $tmp = $file['tmp_name'];

    $info = getimagesize($tmp);
    if ($info === false) {
        die("Invalid image");
    }

    [, , $type] = $info;

    $ext  = image_type_to_extension($type, false);
    $name = time() . "_front_" . pathinfo($file['name'], PATHINFO_FILENAME) . "." . $ext;
    $path = $uploadDir . $name;

    switch ($type) {
        case IMAGETYPE_JPEG:
            $src = imagecreatefromjpeg($tmp);
            imagejpeg($src, $path, 70);
            break;

        case IMAGETYPE_PNG:
            $src = imagecreatefrompng($tmp);
            imagealphablending($src, false);
            imagesavealpha($src, true);
            imagepng($src, $path, 6);
            break;

        case IMAGETYPE_GIF:
            $src = imagecreatefromgif($tmp);
            imagegif($src, $path);
            break;

        case IMAGETYPE_WEBP:
            $src = imagecreatefromwebp($tmp);
            imagewebp($src, $path, 70);
            break;

        case IMAGETYPE_BMP:
            $src = imagecreatefrombmp($tmp);
            imagebmp($src, $path);
            break;

        default:
            die("Unsupported image format");
    }

    imagedestroy($src);
    return $name;
}


/* ================= ADD ================= */
if(isset($_POST['add'])){
    $title = mysqli_real_escape_string($conn,$_POST['title']);
    $subtitle = mysqli_real_escape_string($conn,$_POST['subtitle']);
    $description = mysqli_real_escape_string($conn,$_POST['description']);
    $button_text = mysqli_real_escape_string($conn,$_POST['button_text']);
    $button_link = mysqli_real_escape_string($conn,$_POST['button_link']);

    $bg_image = uploadBgImage($_FILES['image'], $uploadDir);
    $front_image = uploadFrontImage($_FILES['front_image'], $uploadDir);

    mysqli_query($conn,"INSERT INTO sliders
    (title,subtitle,description,button_text,button_link,image,front_image,position,status)
    VALUES
    ('$title','$subtitle','$description','$button_text','$button_link',
     '$bg_image','$front_image',0,1)");

    header("Location: admin-sliders.php");
    exit;
}

/* ================= UPDATE ================= */
if(isset($_POST['update'])){
    $id = $_POST['id'];
    $title = mysqli_real_escape_string($conn,$_POST['title']);
    $subtitle = mysqli_real_escape_string($conn,$_POST['subtitle']);
    $description = mysqli_real_escape_string($conn,$_POST['description']);
    $button_text = mysqli_real_escape_string($conn,$_POST['button_text']);
    $button_link = mysqli_real_escape_string($conn,$_POST['button_link']);

    // FETCH OLD DATA
    $old = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM sliders WHERE id='$id'"));

    $bg_image = $old['image'];
    $front_image = $old['front_image'];

    if(!empty($_FILES['image']['name'])){
        if(file_exists($uploadDir.$old['image'])){
            unlink($uploadDir.$old['image']);
        }
        $bg_image = uploadBgImage($_FILES['image'], $uploadDir);
    }

    if(!empty($_FILES['front_image']['name'])){
        if(file_exists($uploadDir.$old['front_image'])){
            unlink($uploadDir.$old['front_image']);
        }
        $front_image = uploadFrontImage($_FILES['front_image'], $uploadDir);
    }

    mysqli_query($conn,"UPDATE sliders SET
        title='$title',
        subtitle='$subtitle',
        description='$description',
        button_text='$button_text',
        button_link='$button_link',
        image='$bg_image',
        front_image='$front_image'
    WHERE id='$id'");

    header("Location: admin-sliders.php");
    exit;
}

/* ================= DELETE ================= */
if(isset($_GET['del'])){
    $id = $_GET['del'];
    $old = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM sliders WHERE id='$id'"));

    if(file_exists($uploadDir.$old['image'])) unlink($uploadDir.$old['image']);
    if(file_exists($uploadDir.$old['front_image'])) unlink($uploadDir.$old['front_image']);

    mysqli_query($conn,"DELETE FROM sliders WHERE id='$id'");
    header("Location: admin-sliders.php");
    exit;
}

/* ================= STATUS ================= */
if(isset($_GET['status'])){
    $id = $_GET['id'];
    $st = $_GET['status']==1?0:1;
    mysqli_query($conn,"UPDATE sliders SET status='$st' WHERE id='$id'");
    header("Location: admin-sliders.php");
    exit;
}

/* ================= EDIT FETCH ================= */
$editData = null;
if(isset($_GET['edit'])){
    $editData = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM sliders WHERE id=".$_GET['edit']));
}

/* ================= FETCH ================= */
$data = mysqli_query($conn,"SELECT * FROM sliders ORDER BY position ASC");
?>

<!doctype html>
<html>
<head>
<title>Sliders</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<?php include "sidebar.php"; ?>

<div class="container mt-4">
<h3>Sliders</h3>

<form method="post" enctype="multipart/form-data" class="row g-3 mb-3">
<input type="hidden" name="id" value="<?= $editData['id'] ?? '' ?>">

<div class="col-md-6">
<label>Title</label>
<input class="form-control" name="title" value="<?= $editData['title'] ?? '' ?>" required>
</div>

<div class="col-md-6">
<label>Subtitle</label>
<input class="form-control" name="subtitle" value="<?= $editData['subtitle'] ?? '' ?>" required>
</div>

<div class="col-12">
<label>Description</label>
<textarea class="form-control" name="description" required><?= $editData['description'] ?? '' ?></textarea>
</div>

<div class="col-md-6">
<label>Button Text</label>
<input class="form-control" name="button_text" value="<?= $editData['button_text'] ?? '' ?>" required>
</div>

<div class="col-md-6">
<label>Button Link</label>
<input class="form-control" name="button_link" value="<?= $editData['button_link'] ?? '' ?>" required>
</div>

<div class="col-md-6">
<label>Background Image (1920×700)</label>
<input type="file" name="image" class="form-control" <?= isset($editData)?'':'required' ?>>
<?php if(!empty($editData['image'])){ ?>
<img src="../uploads/<?= $editData['image'] ?>" width="150" class="img-thumbnail mt-2">
<?php } ?>
</div>

<div class="col-md-6">
<label>Front Image</label>
<input type="file" name="front_image" class="form-control">
<?php if(!empty($editData['front_image'])){ ?>
<img src="../uploads/<?= $editData['front_image'] ?>" width="150" class="img-thumbnail mt-2">
<?php } ?>
</div>

<div class="col-12">
<button name="<?= isset($editData)?'update':'add' ?>" class="btn btn-primary">
<?= isset($editData)?'Update':'Add' ?>
</button>
</div>
</form>

<table class="table table-bordered">
<tr><th>ID</th><th>Title</th><th>BG</th><th>Front</th><th>Status</th><th>Actions</th></tr>
<?php while($r=mysqli_fetch_assoc($data)){ ?>
<tr>
<td><?= $r['id'] ?></td>
<td><?= $r['title'] ?></td>
<td><img src="../uploads/<?= $r['image'] ?>" width="60"></td>
<td><img src="../uploads/<?= $r['front_image'] ?>" width="60"></td>
<td>
<a href="?status=<?= $r['status'] ?>&id=<?= $r['id'] ?>">
<?= $r['status']?'Active':'Inactive' ?>
</a>
</td>
<td>
<a href="?edit=<?= $r['id'] ?>">Edit</a> |
<a href="?del=<?= $r['id'] ?>" onclick="return confirm('Delete?')">Delete</a>
</td>
</tr>
<?php } ?>
</table>
</div>
</body>
</html>
