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

// --- DATABASE CONFIGURATION ---
$host = "localhost";
$user = "spartanm_invoice";
$pass = "f+f%h-(};[2mwJ8?";
$dbname = "spartanm_invoice";

$conn = new mysqli($host, $user, $pass, $dbname);

if ($conn->connect_error) {
    die(json_encode(["error" => "Connection failed: " . $conn->connect_error]));
}

// --- SAVE INVOICE ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents("php://input"), true);
    if (!$data) { echo json_encode(["status" => "error", "message" => "No data"]); exit; }

    $stmt = $conn->prepare("INSERT INTO invoices (invoice_number, invoice_date, client_name, total_amount, full_data) VALUES (?, ?, ?, ?, ?)");
    $json_data = json_encode($data); 
    $client = strip_tags($data['billTo']); 
    
    $stmt->bind_param("sssss", $data['invNum'], $data['date'], $client, $data['total'], $json_data);
    
    if ($stmt->execute()) echo json_encode(["status" => "success"]);
    else echo json_encode(["status" => "error", "message" => $stmt->error]);
    $stmt->close();
}

// --- LOAD/DELETE INVOICES ---
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $action = isset($_GET['action']) ? $_GET['action'] : 'list';

    if ($action === 'delete' && isset($_GET['id'])) {
        $id = intval($_GET['id']);
        $stmt = $conn->prepare("DELETE FROM invoices WHERE id = ?");
        $stmt->bind_param("i", $id);
        if ($stmt->execute()) echo json_encode(["status" => "success"]);
        else echo json_encode(["status" => "error"]);
        $stmt->close();
    } else {
        $result = $conn->query("SELECT * FROM invoices ORDER BY id DESC");
        $invoices = [];
        if ($result) {
            while($row = $result->fetch_assoc()) {
                $row['full_data'] = json_decode($row['full_data']);
                $invoices[] = $row;
            }
        }
        echo json_encode($invoices);
    }
}
$conn->close();
?>