<?php
require_once __DIR__ . '/../../../app/Config/config.php';
require_once __DIR__ . '/../../../app/Config/database.php';
require_once __DIR__ . '/../../../app/Models/Company.php';

$pdo = Database::getConnection();
$model = new Company($pdo);

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $id = (int)$_GET['id'];
    echo json_encode($model->find($id));
    exit;
}

$id = (int)$_POST['id'];
$company = $model->find($id);
$logoPath = $company['logo_path'];

if (!empty($_FILES['logo']['name'])) {
    $uploadDir = __DIR__ . '/../../uploads/';
    $fileName = time() . '_' . basename($_FILES['logo']['name']);
    move_uploaded_file($_FILES['logo']['tmp_name'], $uploadDir . $fileName);
    $logoPath = $fileName;
}

$model->update($id, [
    'id' => $id,
    'name' => $_POST['name'],
    'registration_no' => $_POST['registration_no'] ?? null,
    'address' => $_POST['address'] ?? null,
    'phone' => $_POST['phone'],
    'email' => $_POST['email'] ?? null,
    'gst_no' => $_POST['gst_no'],
    'logo_path' => $logoPath
]);

echo "Company updated successfully!";
