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

// Check if user is logged in and is admin
if (!isset($_SESSION['user']['id']) || $_SESSION['user']['role'] !== 'admin') {
    echo json_encode(['status' => 'error', 'message' => 'Access denied']);
    exit();
}

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

$supplierId = (int)$_POST['id'];

try {
    // Check if supplier has purchases
    $checkStmt = $pdo->prepare("SELECT COUNT(*) FROM purchases WHERE supplier_id = ?");
    $checkStmt->execute([$supplierId]);
    $hasPurchases = $checkStmt->fetchColumn() > 0;
    
    if ($hasPurchases) {
        echo json_encode([
            'status' => 'error', 
            'message' => 'Cannot delete supplier with existing purchases'
        ]);
        exit();
    }
    
    // Get supplier name for message
    $nameStmt = $pdo->prepare("SELECT name FROM suppliers WHERE id = ?");
    $nameStmt->execute([$supplierId]);
    $supplierName = $nameStmt->fetchColumn();
    
    // Delete the supplier
    $deleteStmt = $pdo->prepare("DELETE FROM suppliers WHERE id = ?");
    $deleteStmt->execute([$supplierId]);
    
    if ($deleteStmt->rowCount() > 0) {
        echo json_encode([
            'status' => 'success', 
            'message' => "Supplier '$supplierName' deleted successfully"
        ]);
    } else {
        echo json_encode([
            'status' => 'error', 
            'message' => 'Supplier not found or already deleted'
        ]);
    }
    
} catch (PDOException $e) {
    // Check for foreign key constraint violation
    if (strpos($e->getMessage(), 'foreign key constraint') !== false) {
        echo json_encode([
            'status' => 'error', 
            'message' => 'Cannot delete supplier. There are related records in the system.'
        ]);
    } else {
        echo json_encode([
            'status' => 'error', 
            'message' => 'Database error: ' . $e->getMessage()
        ]);
    }
}