<?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':
        $buyer = $data['buyer'];
        $id = $buyer['id'] ?? '';
        $company_id = $_SESSION['company_id'];
        
        if ($id) {
            // Update
            $sql = "UPDATE buyers SET name=?, brand=?, country=?, contact_person=?, email=?, phone=?, status=? WHERE id=? AND company_id=?";
            query($sql, [$buyer['name'], $buyer['brand'], $buyer['country'], $buyer['contact_person'], $buyer['email'], $buyer['phone'], $buyer['status'], $id, $company_id]);
            echo json_encode(['success' => true, 'message' => 'Buyer updated successfully']);
        } else {
            // Create
            $sql = "INSERT INTO buyers (company_id, name, brand, country, contact_person, email, phone, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            query($sql, [$company_id, $buyer['name'], $buyer['brand'], $buyer['country'], $buyer['contact_person'], $buyer['email'], $buyer['phone'], $buyer['status']]);
            echo json_encode(['success' => true, 'message' => 'Buyer added successfully']);
        }
        break;

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

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