<?php
include 'db.php';

if (isset($_POST['login'])) {
    $email = $_POST['email']; $pass = $_POST['password'];
    $res = $conn->query("SELECT * FROM admin_users WHERE email='$email'");
    if ($user = $res->fetch_assoc()) {
        if (password_verify($pass, $user['password'])) { $_SESSION['admin_id'] = $user['id']; header("Location: admin.php"); exit(); }
    }
    header("Location: login.php?error=1");
}
if (isset($_GET['logout'])) { session_destroy(); header("Location: login.php"); }

if (isset($_POST['update_settings'])) {
    if(!isset($_SESSION['admin_id'])) exit;
    $c = $_POST['code_color']; $dc = $_POST['desc_color']; $m = $_POST['m_grid']; $t = $_POST['t_grid']; $dk = $_POST['d_grid'];
    $conn->query("UPDATE site_settings SET code_color='$c', desc_color='$dc', grid_mobile=$m, grid_tablet=$t, grid_desktop=$dk WHERE id=1");
    header("Location: admin.php");
}

if (isset($_POST['upload'])) {
    if(!isset($_SESSION['admin_id'])) exit;
    $t = $_POST['title']; $tg = $_POST['tags']; $c = $_POST['code']; $ds = $_POST['description']; $so = $_POST['sort_order'];
    $path = "uploads/" . time() . "_" . basename($_FILES["image"]["name"]);
    if (move_uploaded_file($_FILES["image"]["tmp_name"], $path)) {
        $stmt = $conn->prepare("INSERT INTO items (image_path, title, tags, code, description, sort_order) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("sssssi", $path, $t, $tg, $c, $ds, $so); $stmt->execute();
    }
    header("Location: admin.php");
}

if (isset($_POST['update_item'])) {
    if(!isset($_SESSION['admin_id'])) exit;
    $id = $_POST['id']; $t = $_POST['title']; $tg = $_POST['tags']; $c = $_POST['code']; $ds = $_POST['description']; $so = $_POST['sort_order'];
    if (!empty($_FILES["image"]["name"])) {
        $path = "uploads/" . time() . "_" . basename($_FILES["image"]["name"]); move_uploaded_file($_FILES["image"]["tmp_name"], $path);
        $stmt = $conn->prepare("UPDATE items SET image_path=?, title=?, tags=?, code=?, description=?, sort_order=? WHERE id=?");
        $stmt->bind_param("sssssii", $path, $t, $tg, $c, $ds, $so, $id);
    } else {
        $stmt = $conn->prepare("UPDATE items SET title=?, tags=?, code=?, description=?, sort_order=? WHERE id=?");
        $stmt->bind_param("sssisi", $t, $tg, $c, $ds, $so, $id);
    }
    $stmt->execute(); header("Location: admin.php");
}

if (isset($_GET['delete'])) {
    if(!isset($_SESSION['admin_id'])) exit;
    $id = $_GET['delete']; $row = $conn->query("SELECT image_path FROM items WHERE id=$id")->fetch_assoc();
    if(file_exists($row['image_path'])) unlink($row['image_path']);
    $conn->query("DELETE FROM items WHERE id=$id"); header("Location: admin.php");
}
?>