<?php
session_start();
error_reporting(0);
include('includes/config.php');

header('Content-Type: application/json');

if (strlen($_SESSION['alogin']) == 0) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
        exit;
    }

    $rackId   = isset($_POST['rackId']) ? intval($_POST['rackId']) : 0;
    $rack_no  = trim($_POST['rackNo'] ?? '');
    $shelf_no = trim($_POST['shelfNo'] ?? '');
    $floor    = trim($_POST['floor'] ?? '');

    if ($rack_no === '' || $shelf_no === '' || $floor === '') {
        echo json_encode(['status' => 'error', 'message' => 'All fields are required']);
        exit;
    }

    if ($rackId > 0) {
        // ✅ Update
        $sql = "UPDATE tbl_racks
                SET rack_no = :rack_no, shelf_no = :shelf_no, floor = :floor
                WHERE id = :id";
        $query = $dbh->prepare($sql);
        $query->bindParam(':rack_no', $rack_no, PDO::PARAM_STR);
        $query->bindParam(':shelf_no', $shelf_no, PDO::PARAM_STR);
        $query->bindParam(':floor', $floor, PDO::PARAM_STR);
        $query->bindParam(':id', $rackId, PDO::PARAM_INT);
        $query->execute();

        echo json_encode(['status' => 'success', 'message' => 'Rack updated successfully']);
        exit;
    } else {
        // ✅ Insert
        $sql = "INSERT INTO tbl_racks (rack_no, shelf_no, floor)
                VALUES (:rack_no, :shelf_no, :floor)";
        $query = $dbh->prepare($sql);
        $query->bindParam(':rack_no', $rack_no, PDO::PARAM_STR);
        $query->bindParam(':shelf_no', $shelf_no, PDO::PARAM_STR);
        $query->bindParam(':floor', $floor, PDO::PARAM_STR);
        $query->execute();

        echo json_encode(['status' => 'success', 'message' => 'Rack added successfully']);
        exit;
    }
} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    exit;
}
