<?php

header('Content-Type: text/plain');
include 'config.php';

/* =========================
   ADMIN AUTH CHECK
   ========================= */

$admin_username = $_POST['admin_username'] ?? '';
$admin_password = $_POST['admin_password'] ?? '';

$admin_stmt = $conn->prepare(
    "SELECT 1 FROM admin WHERE username = ? AND password = ?"
);

$admin_stmt->bind_param("ss", $admin_username, $admin_password);
$admin_stmt->execute();
$admin_result = $admin_stmt->get_result();

if ($admin_result->num_rows === 0) {
    echo "Access Denied";
    $admin_stmt->close();
    $conn->close();
    exit();
}

$admin_stmt->close();

/* =========================
   TYPE HANDLER
   ========================= */

$type = $_POST['type'] ?? '';

/* =========================
   ADD CATEGORY
   ========================= */

if ($type == "add") {

    $title = trim($_POST['title'] ?? '');
    $image_link = trim($_POST['image_link'] ?? '');

    if (empty($title) || empty($image_link)) {
        echo "Title and Image Link Required";
        $conn->close();
        exit();
    }

    $stmt = $conn->prepare(
        "INSERT INTO category (title, image_link) VALUES (?, ?)"
    );

    $stmt->bind_param("ss", $title, $image_link);

    if ($stmt->execute()) {
        echo "Category Added Successfully";
    } else {
        echo "Failed To Add Category";
    }

    $stmt->close();
}

/* =========================
   DELETE CATEGORY
   ========================= */

elseif ($type == "delete") {

    $id = $_POST['id'] ?? '';

    if (empty($id)) {
        echo "ID Required";
        $conn->close();
        exit();
    }

    $stmt = $conn->prepare(
        "DELETE FROM category WHERE id = ?"
    );

    $stmt->bind_param("i", $id);

    if ($stmt->execute()) {
        echo "Category Deleted Successfully";
    } else {
        echo "Failed To Delete Category";
    }

    $stmt->close();
}

/* =========================
   UPDATE CATEGORY
   ========================= */

elseif ($type == "update") {

    $id = $_POST['id'] ?? '';
    $title = trim($_POST['title'] ?? '');
    $image_link = trim($_POST['image_link'] ?? '');

    if (empty($id) || empty($title) || empty($image_link)) {
        echo "ID, Title and Image Link Required";
        $conn->close();
        exit();
    }

    $stmt = $conn->prepare(
        "UPDATE category SET title = ?, image_link = ? WHERE id = ?"
    );

    $stmt->bind_param("ssi", $title, $image_link, $id);

    if ($stmt->execute()) {
        echo "Category Updated Successfully";
    } else {
        echo "Failed To Update Category";
    }

    $stmt->close();
}

else {
    echo "Invalid Type";
}

$conn->close();

?>