<?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';
require_once __DIR__ . '/../models/Item.php';

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

$item = new Item($db);

$request_method = $_SERVER['REQUEST_METHOD'];

switch($request_method) {
    case 'GET':
        if(isset($_GET['id'])) {
            $item->id = $_GET['id'];
            $item->readOne();
            
            if($item->name != null) {
                // Fix picture URL if it contains incorrect path
                $picture_url = $item->picture;
                if ($picture_url && strpos($picture_url, '/var/www/html/') !== false) {
                    // Remove /var/www/html/ from the path
                    $picture_url = str_replace('/var/www/html/', '', $picture_url);
                }
                if ($picture_url && strpos($picture_url, '/api/') !== false) {
                    // Remove /api/ from the beginning if present
                    $picture_url = str_replace('/api/', '', $picture_url);
                }
                // Use relative URL to avoid mixed content warnings
                if ($picture_url && !preg_match('/^https?:\/\//', $picture_url)) {
                    $picture_url = '/' . ltrim($picture_url, '/');
                }
                
                $item_arr = array(
                    "id" => $item->id,
                    "name" => $item->name,
                    "description" => $item->description,
                    "serial_number" => $item->serial_number,
                    "picture" => $picture_url,
                    "quantity" => $item->quantity,
                    "price" => $item->price,
                    "date_of_purchase" => $item->date_of_purchase,
                    "created_at" => $item->created_at,
                    "updated_at" => $item->updated_at
                );
                
                http_response_code(200);
                echo json_encode($item_arr);
            } else {
                http_response_code(404);
                echo json_encode(array("message" => "Item not found."));
            }
        } else {
            $stmt = $item->read();
            $num = $stmt->rowCount();
            
            if($num > 0) {
                $items_arr = array();
                $items_arr["records"] = array();
                
                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                    extract($row);
                    
                    // Fix picture URL if it contains incorrect path
                    $picture_url = $picture;
                    if ($picture && strpos($picture, '/var/www/html/') !== false) {
                        // Remove /var/www/html/ from the path
                        $picture_url = str_replace('/var/www/html/', '', $picture);
                    }
                    if ($picture && strpos($picture, '/api/') !== false) {
                        // Remove /api/ from the beginning if present
                        $picture_url = str_replace('/api/', '', $picture);
                    }
                    // Use relative URL to avoid mixed content warnings
                    if ($picture_url && !preg_match('/^https?:\/\//', $picture_url)) {
                        $picture_url = '/' . ltrim($picture_url, '/');
                    }
                    
                    $item_item = array(
                        "id" => $id,
                        "name" => $name,
                        "description" => $description,
                        "serial_number" => $serial_number,
                        "picture" => $picture_url,
                        "quantity" => $quantity,
                        "price" => $price,
                        "date_of_purchase" => $date_of_purchase,
                        "created_at" => $created_at,
                        "updated_at" => $updated_at
                    );
                    
                    array_push($items_arr["records"], $item_item);
                }
                
                http_response_code(200);
                echo json_encode($items_arr);
            } else {
                http_response_code(200);
                echo json_encode(array("records" => array()));
            }
        }
        break;
        
    case 'POST':
        $data = json_decode(file_get_contents("php://input"));
        
        if(!empty($data->name) && !empty($data->quantity) && !empty($data->price)) {
            $item->name = $data->name;
            $item->description = $data->description ?? '';
            $item->serial_number = $data->serial_number ?? '';
            $item->picture = $data->picture ?? '';
            $item->quantity = $data->quantity;
            $item->price = $data->price;
            $item->date_of_purchase = $data->date_of_purchase ?? null;
            
            if($item->create()) {
                // Create corresponding accounting entry
                require_once __DIR__ . '/../models/AccountingEntry.php';
                $accounting_entry = new AccountingEntry($db);
                
                // Calculate accounting entry fields
                $total_amount = floatval($data->price) * intval($data->quantity);
                $vat_percentage = 25.50;
                $net_amount = $total_amount / (1 + ($vat_percentage / 100));
                $vat_amount = $total_amount - $net_amount;
                $tax_free_amount = $net_amount;
                
                // Set accounting entry properties
                $accounting_entry->entry_date = $data->date_of_purchase ?? date('Y-m-d');
                $accounting_entry->description = $data->name;
                $accounting_entry->entry_type = 'Kulu';
                $accounting_entry->category = '333';
                $accounting_entry->tax_free_amount = $tax_free_amount;
                $accounting_entry->vat_percentage = $vat_percentage;
                $accounting_entry->vat_25_5 = $vat_amount;
                $accounting_entry->vat_14 = 0;
                $accounting_entry->vat_10 = 0;
                $accounting_entry->total_amount = $total_amount;
                $accounting_entry->net_amount = $net_amount;
                $accounting_entry->vat_amount = $vat_amount;
                $accounting_entry->reference_number = '';
                
                // Create accounting entry
                if($accounting_entry->create()) {
                    http_response_code(201);
                    echo json_encode(array("message" => "Item and accounting entry were created."));
                } else {
                    http_response_code(201);
                    echo json_encode(array("message" => "Item was created but accounting entry failed."));
                }
            } else {
                http_response_code(503);
                echo json_encode(array("message" => "Unable to create item."));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Unable to create item. Data is incomplete."));
        }
        break;
        
    case 'PUT':
        $data = json_decode(file_get_contents("php://input"));
        
        if(!empty($data->id) && !empty($data->name) && !empty($data->quantity) && !empty($data->price)) {
            $item->id = $data->id;
            $item->name = $data->name;
            $item->description = $data->description ?? '';
            $item->serial_number = $data->serial_number ?? '';
            $item->picture = $data->picture ?? '';
            $item->quantity = $data->quantity;
            $item->price = $data->price;
            $item->date_of_purchase = $data->date_of_purchase ?? null;
            
            if($item->update()) {
                // Update or create corresponding accounting entry
                require_once __DIR__ . '/../models/AccountingEntry.php';
                $accounting_entry = new AccountingEntry($db);
                
                // Calculate accounting entry fields
                $total_amount = floatval($data->price) * intval($data->quantity);
                $vat_percentage = 25.50;
                $net_amount = $total_amount / (1 + ($vat_percentage / 100));
                $vat_amount = $total_amount - $net_amount;
                $tax_free_amount = $net_amount;
                
                // Set accounting entry properties
                $accounting_entry->entry_date = $data->date_of_purchase ?? date('Y-m-d');
                $accounting_entry->description = $data->name;
                $accounting_entry->entry_type = 'Kulu';
                $accounting_entry->category = '333';
                $accounting_entry->tax_free_amount = $tax_free_amount;
                $accounting_entry->vat_percentage = $vat_percentage;
                $accounting_entry->vat_25_5 = $vat_amount;
                $accounting_entry->vat_14 = 0;
                $accounting_entry->vat_10 = 0;
                $accounting_entry->total_amount = $total_amount;
                $accounting_entry->net_amount = $net_amount;
                $accounting_entry->vat_amount = $vat_amount;
                $accounting_entry->reference_number = '';
                
                // Try to find existing accounting entry for this item
                $existing_entry_query = "SELECT id FROM accounting_entries WHERE description = ? AND entry_type = 'Kulu' AND category = '333' ORDER BY entry_date DESC LIMIT 1";
                $stmt = $db->prepare($existing_entry_query);
                $stmt->execute([$data->name]);
                $existing_entry = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($existing_entry) {
                    // Update existing entry
                    $accounting_entry->id = $existing_entry['id'];
                    if($accounting_entry->update()) {
                        http_response_code(200);
                        echo json_encode(array("message" => "Item and accounting entry were updated."));
                    } else {
                        http_response_code(200);
                        echo json_encode(array("message" => "Item was updated but accounting entry update failed."));
                    }
                } else {
                    // Create new entry
                    if($accounting_entry->create()) {
                        http_response_code(200);
                        echo json_encode(array("message" => "Item was updated and new accounting entry was created."));
                    } else {
                        http_response_code(200);
                        echo json_encode(array("message" => "Item was updated but accounting entry creation failed."));
                    }
                }
            } else {
                http_response_code(503);
                echo json_encode(array("message" => "Unable to update item."));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Unable to update item. Data is incomplete."));
        }
        break;
        
    case 'DELETE':
        if(isset($_GET['id'])) {
            $item->id = $_GET['id'];
            
            if($item->delete()) {
                http_response_code(200);
                echo json_encode(array("message" => "Item was deleted."));
            } else {
                http_response_code(503);
                echo json_encode(array("message" => "Unable to delete item."));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Unable to delete item. ID is missing."));
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(array("message" => "Method not allowed."));
        break;
}
?>
