<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit(0);
}

require_once __DIR__ . '/../config/database.php';

$database = new Database();
$db = $database->getConnection();

$request_method = $_SERVER['REQUEST_METHOD'];

switch($request_method) {
    case 'GET':
        if(isset($_GET['type'])) {
            // Get categories by type (Tulo/Kulu)
            $type = $_GET['type'];
            $query = "SELECT category_code, category_name, category_type, vat_percentage 
                      FROM accounting_categories 
                      WHERE category_type = ? AND is_active = 1 
                      ORDER BY category_code";
            
            $stmt = $db->prepare($query);
            $stmt->bindParam(1, $type);
            $stmt->execute();
            
            $categories = [];
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $categories[] = [
                    'code' => $row['category_code'],
                    'name' => $row['category_name'],
                    'type' => $row['category_type'],
                    'vat_percentage' => $row['vat_percentage']
                ];
            }
            
            http_response_code(200);
            echo json_encode($categories);
        } else {
            // Get all categories
            $query = "SELECT category_code, category_name, category_type, vat_percentage 
                      FROM accounting_categories 
                      WHERE is_active = 1 
                      ORDER BY category_type, category_code";
            
            $stmt = $db->prepare($query);
            $stmt->execute();
            
            $categories = [];
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $categories[] = [
                    'code' => $row['category_code'],
                    'name' => $row['category_name'],
                    'type' => $row['category_type'],
                    'vat_percentage' => $row['vat_percentage']
                ];
            }
            
            http_response_code(200);
            echo json_encode($categories);
        }
        break;
        
    case 'POST':
        $data = json_decode(file_get_contents("php://input"));
        
        if(!empty($data->category_code) && !empty($data->category_name) && !empty($data->category_type)) {
            $query = "INSERT INTO accounting_categories 
                      SET category_code=:category_code, 
                          category_name=:category_name, 
                          category_type=:category_type, 
                          vat_percentage=:vat_percentage, 
                          is_active=:is_active";
            
            $stmt = $db->prepare($query);
            
            $stmt->bindParam(":category_code", $data->category_code);
            $stmt->bindParam(":category_name", $data->category_name);
            $stmt->bindParam(":category_type", $data->category_type);
            $stmt->bindParam(":vat_percentage", $data->vat_percentage);
            $stmt->bindParam(":is_active", $data->is_active ?? 1);
            
            if($stmt->execute()) {
                http_response_code(201);
                echo json_encode(array("message" => "Category was created."));
            } else {
                http_response_code(503);
                echo json_encode(array("message" => "Unable to create category."));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Unable to create category. Data is incomplete."));
        }
        break;
        
    case 'PUT':
        $data = json_decode(file_get_contents("php://input"));
        
        if(!empty($data->category_code) && !empty($data->category_name) && !empty($data->category_type)) {
            $query = "UPDATE accounting_categories 
                      SET category_name=:category_name, 
                          category_type=:category_type, 
                          vat_percentage=:vat_percentage, 
                          is_active=:is_active 
                      WHERE category_code=:category_code";
            
            $stmt = $db->prepare($query);
            
            $stmt->bindParam(":category_code", $data->category_code);
            $stmt->bindParam(":category_name", $data->category_name);
            $stmt->bindParam(":category_type", $data->category_type);
            $stmt->bindParam(":vat_percentage", $data->vat_percentage);
            $stmt->bindParam(":is_active", $data->is_active ?? 1);
            
            if($stmt->execute()) {
                http_response_code(200);
                echo json_encode(array("message" => "Category was updated."));
            } else {
                http_response_code(503);
                echo json_encode(array("message" => "Unable to update category."));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Unable to update category. Data is incomplete."));
        }
        break;
        
    case 'DELETE':
        if(isset($_GET['code'])) {
            $code = $_GET['code'];
            $query = "DELETE FROM accounting_categories WHERE category_code = ?";
            
            $stmt = $db->prepare($query);
            $stmt->bindParam(1, $code);
            
            if($stmt->execute()) {
                http_response_code(200);
                echo json_encode(array("message" => "Category was deleted."));
            } else {
                http_response_code(503);
                echo json_encode(array("message" => "Unable to delete category."));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Unable to delete category. Category code is missing."));
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(array("message" => "Method not allowed."));
        break;
}
?>
