<?php
session_start();
require_once '../assets/db_connect.php';

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

// Must be logged in
if (!isset($_SESSION['user']['id']) || !isset($_SESSION['user']['shop_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

$current_shop = $_SESSION['user']['shop_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (!isset($_POST['id']) || empty($_POST['id'])) {
        echo json_encode(['status' => 'error', 'message' => 'Purchase ID missing']);
        exit;
    }

    $purchase_id = intval($_POST['id']);

    try {

        // Check shop ownership first
        $check = $pdo->prepare("SELECT shop_id FROM purchases WHERE id = ?");
        $check->execute([$purchase_id]);
        $purchase = $check->fetch();

        if (!$purchase) {
            echo json_encode(['status' => 'error', 'message' => 'Purchase not found']);
            exit;
        }

        if ($purchase['shop_id'] != $current_shop) {
            echo json_encode(['status' => 'error', 'message' => 'Access denied. Not your shop.']);
            exit;
        }

        // DELETE purchase lines
        $delLines = $pdo->prepare("DELETE FROM purchase_lines WHERE purchase_id = ?");
        $delLines->execute([$purchase_id]);

        // DELETE purchase record
        $delPurchase = $pdo->prepare("DELETE FROM purchases WHERE id = ?");
        $delPurchase->execute([$purchase_id]);

        echo json_encode(['status' => 'success', 'message' => 'Purchase deleted successfully']);

    } catch (PDOException $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }

} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
}
