<?php
require_once '../includes/auth.php';
require_once '../includes/db.php';

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

if (!isLoggedIn() || !hasRole(['owner', 'admin', 'manager', 'supervisor'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);
$action = $data['action'] ?? '';

switch ($action) {
    case 'save':
        $supplier = $data['supplier'];
        $id = $supplier['id'] ?? '';
        $company_id = $_SESSION['company_id'];
        
        if ($id) {
            $sql = "UPDATE suppliers SET name=?, category=?, lead_time=?, contact_person=?, email=?, phone=?, rating=?, status=? WHERE id=? AND company_id=?";
            query($sql, [$supplier['name'], $supplier['category'], $supplier['lead_time'], $supplier['contact_person'], $supplier['email'], $supplier['phone'], $supplier['rating'], $supplier['status'], $id, $company_id]);
            echo json_encode(['success' => true, 'message' => 'Supplier updated successfully']);
        } else {
            $sql = "INSERT INTO suppliers (company_id, name, category, lead_time, contact_person, email, phone, rating, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
            query($sql, [$company_id, $supplier['name'], $supplier['category'], $supplier['lead_time'], $supplier['contact_person'], $supplier['email'], $supplier['phone'], $supplier['rating'], $supplier['status']]);
            echo json_encode(['success' => true, 'message' => 'Supplier added successfully']);
        }
        break;

    case 'delete':
        $id = $data['id'];
        $company_id = $_SESSION['company_id'];
        query("DELETE FROM suppliers WHERE id = ? AND company_id = ?", [$id, $company_id]);
        echo json_encode(['success' => true, 'message' => 'Supplier deleted successfully']);
        break;

    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
        break;
}
