<?php
include_once('includes/config.php');





// show PHP errors
ini_set('display_errors', 1);

// output any connection error
if ($mysqli->connect_error) {
    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}

$action = isset($_POST['action']) ? $_POST['action'] : "";

// Create customer
if ($action === 'create_customer') {

    header('Content-Type: application/json');
    session_start();

    /* =========================
       COMPANY CONTEXT
    ========================== */
    if (empty($_SESSION['company_id'])) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Company context missing. Please re-login.'
        ]);
        exit;
    }

    $company_id = (int) $_SESSION['company_id'];

    /* =========================
       BASIC VALIDATION
    ========================== */
    if (empty($_POST['customer_name'])) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Customer name is required.'
        ]);
        exit;
    }

    /* =========================
       BILLING INFO
    ========================== */
    $customer_name      = trim($_POST['customer_name']);
    $customer_email     = trim($_POST['customer_email'] ?? '');
    $customer_address_1 = trim($_POST['customer_address_1'] ?? '');
    $customer_address_2 = trim($_POST['customer_address_2'] ?? '');
    $customer_town      = trim($_POST['customer_town'] ?? '');
    $customer_county    = trim($_POST['customer_county'] ?? '');
    $customer_postcode  = trim($_POST['customer_postcode'] ?? '');
    $customer_phone     = trim($_POST['customer_phone'] ?? '');

    /* =========================
       SHIPPING INFO
    ========================== */
    $customer_name_ship      = trim($_POST['customer_name_ship'] ?? '');
    $customer_address_1_ship = trim($_POST['customer_address_1_ship'] ?? '');
    $customer_address_2_ship = trim($_POST['customer_address_2_ship'] ?? '');
    $customer_town_ship      = trim($_POST['customer_town_ship'] ?? '');
    $customer_county_ship    = trim($_POST['customer_county_ship'] ?? '');
    $customer_postcode_ship  = trim($_POST['customer_postcode_ship'] ?? '');

    /* =========================
       INSERT CUSTOMER
    ========================== */
    $stmt = $mysqli->prepare("
        INSERT INTO store_customers (
            company_id,
            name,
            email,
            address_1,
            address_2,
            town,
            county,
            postcode,
            phone,
            name_ship,
            address_1_ship,
            address_2_ship,
            town_ship,
            county_ship,
            postcode_ship
        ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
    ");

    if (!$stmt) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Database prepare failed'
        ]);
        exit;
    }

    $stmt->bind_param(
        'issssssssssssss',
        $company_id,
        $customer_name,
        $customer_email,
        $customer_address_1,
        $customer_address_2,
        $customer_town,
        $customer_county,
        $customer_postcode,
        $customer_phone,
        $customer_name_ship,
        $customer_address_1_ship,
        $customer_address_2_ship,
        $customer_town_ship,
        $customer_county_ship,
        $customer_postcode_ship
    );

    if ($stmt->execute()) {
        echo json_encode([
            'status'  => 'Success',
            'message' => 'Customer created successfully'
        ]);
    } else {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Unable to create customer'
        ]);
    }

    $stmt->close();
    $mysqli->close();
    exit;
}

// Create Voucher
if ($action === 'create_voucher') {

    function syncVoucherCounter(mysqli $mysqli, int $company_id, int $usedVoucher): void
    {
        $stmt = $mysqli->prepare("
            UPDATE company
            SET voucher_counter = GREATEST(voucher_counter, ?)
            WHERE id = ?
        ");
        $stmt->bind_param("ii", $usedVoucher, $company_id);
        $stmt->execute();
    }

    header('Content-Type: application/json');
    session_start();

    if (!isset($_SESSION['company_id'])) {
        echo json_encode([
            'status'  => 'error',
            'message' => 'Company context missing. Please re-login.'
        ]);
        exit;
    }

    $company_id = (int) $_SESSION['company_id'];

    // --- DB CONNECTION ---
    $mysqli = new mysqli(DATABASE_HOST, DATABASE_USER, DATABASE_PASS, DATABASE_NAME);
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

    try {

        $mysqli->begin_transaction();

        /* =========================
           VOUCHER NUMBER LOGIC
        ========================== */
        $userVoucher    = trim($_POST['voucher_id']);
        $previewVoucher = trim($_POST['preview_voucher_number']);

        if ($userVoucher === $previewVoucher) {
            // User accepted preview → atomic increment
            $finalVoucher = reserveVoucherNumber($mysqli, $company_id);
        } else {

            if ($userVoucher !== '') {
                $finalVoucher = (int) $userVoucher;

                // Keep counter in sync
                syncVoucherCounter($mysqli, $company_id, $finalVoucher + 1);
            } else {
                $finalVoucher = reserveVoucherNumber($mysqli, $company_id);
            }
        }

        /* =========================
           TOTALS
        ========================== */
        $vat       = (float) ($_POST['invoice_vat'] ?? 0);
        $discount  = (float) ($_POST['invoicediscount'] ?? 0);
        $subtotal  = (float) ($_POST['invoice_subtotal'] ?? 0);
        $total     = (float) ($_POST['invoice_total'] ?? 0);

        /* =========================
           INSERT VOUCHER (MASTER)
        ========================== */
        $stmt = $mysqli->prepare("
            INSERT INTO vouchers (
                company_id,
                voucher_id,
                voucher_date,
                requested_by,
                voucher_dept,
                short_title,
                payment_mode,
                ben_account_name,
                ben_account_no,
                bank,
                subtotal,
                discount,
                vat,
                total,
                created_by,
                notes,
                payment_by,
                approved_by,
                approved_by2
            ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
        ");

        $stmt->bind_param(
            "isssssssssddddsssss",
            $company_id,
            $finalVoucher,
            $_POST['voucher_date'],
            $_POST['requested_by'],
            $_POST['voucher_dept'],
            $_POST['short_title'],
            $_POST['payment_mode'],
            $_POST['ben_account_name'],
            $_POST['ben_account_no'],
            $_POST['bank'],
            $subtotal,
            $discount,
            $vat,
            $total,
            $_POST['created_by'],
            $_POST['notes'],
            $_POST['payment_by'],
            $_POST['approved_by'],
            $_POST['approved_by2']
        );

        $stmt->execute();

        /* =========================
           INSERT VOUCHER ITEMS
        ========================== */
        $itemStmt = $mysqli->prepare("
            INSERT INTO voucher_items (
                company_id,
                invoice,
                product,
                product_description,
                qty,
                price,
                discount,
                subtotal,
                item_order
            ) VALUES (?,?,?,?,?,?,?,?,?)
        ");

        foreach ($_POST['invoice_product'] as $i => $product) {

            if (trim($product) === '') continue;

            $qty   = (float) $_POST['invoice_product_qty'][$i];
            $price = (float) $_POST['invoice_product_price'][$i];
            $disc  = (float) ($_POST['invoice_product_discount'][$i] ?? 0);
            $sub   = ($qty * $price) - $disc;

            $itemStmt->bind_param(
                "isssddddi",
                $company_id,
                $finalVoucher,
                $product,
                $_POST['invoice_product_description'][$i],
                $qty,
                $price,
                $disc,
                $sub,
                $i
            );

            $itemStmt->execute();
        }

        $mysqli->commit();

        echo json_encode([
            'status'  => 'success',
            'message' => 'Voucher created successfully',
            'voucher' => $finalVoucher
        ]);

    } catch (Throwable $e) {

        $mysqli->rollback();

        echo json_encode([
            'status'  => 'error',
            'message' => $e->getMessage()
        ]);
    }

    $mysqli->close();
    exit;
}


//update voucher
if ($action === 'update_voucher') {

    header('Content-Type: application/json');
    session_start();

    if (!isset($_SESSION['company_id'])) {
        echo json_encode([
            "status"  => "error",
            "message" => "Company context missing. Please re-login."
        ]);
        exit;
    }

    $company_id = (int) $_SESSION['company_id'];

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

    try {
        $mysqli->begin_transaction();

        $voucher_id = trim($_POST['voucher_id']); // STRING voucher code

        if ($voucher_id === '') {
            throw new Exception("Invalid voucher reference");
        }

        /* =========================
           VALIDATE ITEMS
        ========================== */
        if (empty($_POST['invoice_product']) || !is_array($_POST['invoice_product'])) {
            throw new Exception("No voucher items supplied");
        }

        $discount = !empty($_POST['invoicediscount']) ? (float) $_POST['invoicediscount'] : 0.00;
        $subtotal = !empty($_POST['invoice_subtotal']) ? (float) $_POST['invoice_subtotal'] : 0.00;
        $total    = !empty($_POST['invoice_total']) ? (float) $_POST['invoice_total'] : 0.00;

        /* =========================
           UPDATE VOUCHER (SAFE)
        ========================== */
        $stmt = $mysqli->prepare("
            UPDATE vouchers SET
                voucher_date = ?,
                requested_by = ?,
                voucher_dept = ?,
                short_title  = ?,
                payment_mode = ?,
                ben_account_name = ?,
                ben_account_no   = ?,
                bank = ?,
                discount = ?,
                subtotal = ?,
                total = ?,
                notes = ?,
                created_by = ?,
                payment_by = ?,
                approved_by = ?,
                approved_by2 = ?
            WHERE voucher_id = ?
              AND company_id = ?
        ");

				$stmt->bind_param(
			"ssssssssdddssssssi",
			$_POST['voucher_date'],
			$_POST['requested_by'],
			$_POST['voucher_dept'],
			$_POST['short_title'],
			$_POST['payment_mode'],
			$_POST['ben_account_name'],
			$_POST['ben_account_no'],
			$_POST['bank'],
			$discount,
			$subtotal,
			$total,
			$_POST['notes'],
			$_POST['created_by'],
			$_POST['payment_by'],
			$_POST['approved_by'],
			$_POST['approved_by2'],
			$voucher_id,
			$company_id
		);


        $stmt->execute();

        if ($stmt->affected_rows === 0) {
            throw new Exception("Voucher not found or access denied");
        }

        /* =========================
           DELETE OLD ITEMS (SAFE)
        ========================== */
        $del = $mysqli->prepare("
            DELETE FROM voucher_items
            WHERE invoice = ?
              AND company_id = ?
        ");
        $del->bind_param("si", $voucher_id, $company_id);
        $del->execute();

        /* =========================
           INSERT NEW ITEMS
        ========================== */
        $itemStmt = $mysqli->prepare("
            INSERT INTO voucher_items (
                company_id,
                invoice,
                product,
                product_description,
                qty,
                price,
                discount,
                subtotal,
                item_order
            ) VALUES (?,?,?,?,?,?,?,?,?)
        ");

        foreach ($_POST['invoice_product'] as $i => $product) {

            if (trim($product) === '') continue;

            $qty   = (float) $_POST['invoice_product_qty'][$i];
            $price = (float) $_POST['invoice_product_price'][$i];
            $itemDiscount = !empty($_POST['invoice_product_discount'][$i])
                ? (float) $_POST['invoice_product_discount'][$i]
                : 0.00;

            $lineSubtotal = ($qty * $price) - $itemDiscount;

            $itemStmt->bind_param(
                "isssddddi",
                $company_id,
                $voucher_id,
                $product,
                $_POST['invoice_product_description'][$i],
                $qty,
                $price,
                $itemDiscount,
                $lineSubtotal,
                $i
            );

            $itemStmt->execute();
        }

        $mysqli->commit();

        echo json_encode([
            "status"  => "success",
            "message" => "Voucher updated successfully"
        ]);

    } catch (Throwable $e) {

        $mysqli->rollback();

        echo json_encode([
            "status"  => "error",
            "message" => $e->getMessage()
        ]);
    }

    exit;
}




// Create Invoice
if ($action === 'create_invoice') {

function syncInvoiceCounter(mysqli $mysqli, int $company_id, int $usedInvoice): void
{
    $stmt = $mysqli->prepare("
        UPDATE company
        SET invoice_counter = GREATEST(invoice_counter, ?)
        WHERE id = ?
    ");
    $stmt->bind_param("ii", $usedInvoice, $company_id);
    $stmt->execute();
}


    header('Content-Type: application/json');
    session_start();

    if (!isset($_SESSION['company_id'])) {
        echo json_encode([
            'status' => 'error',
            'message' => 'Company context missing. Please re-login.'
        ]);
        exit;
    }

    $company_id = (int) $_SESSION['company_id'];
	
	

    // --- DB CONNECTION ---
    $mysqli = new mysqli(DATABASE_HOST, DATABASE_USER, DATABASE_PASS, DATABASE_NAME);
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

    try {

        $mysqli->begin_transaction();

		$userInvoice = trim($_POST['invoice']);
		$previewInvoice  = trim($_POST['preview_invoice_number']);

        if ($userInvoice === $previewInvoice) {
            // User accepted preview → atomic increment
            $invoice_number = reserveInvoiceNumber($mysqli, $company_id);
        } else {
				if ($userInvoice !== '') {

    $finalInvoice = (int) $userInvoice;

    // Keep counter in sync
    syncInvoiceCounter($mysqli, $company_id, $finalInvoice + 1);

} else {

    $finalInvoice = reserveInvoiceNumber($mysqli, $company_id);
}


        }

        /* =========================
           INVOICE DATA
        ========================== */
        
        $invoice_date     = $_POST['invoice_date'];
        $invoice_due_date = $_POST['invoice_due_date'];

        $subtotal  = (float) ($_POST['invoice_subtotal'] ?? 0);
        $shipping  = (float) ($_POST['invoice_shipping'] ?? 0);
        $discount  = (float) ($_POST['invoicediscount'] ?? 0);
        $vat       = (float) ($_POST['invoice_vat'] ?? 0);
        $total     = (float) ($_POST['invoice_total'] ?? 0);

        /* =========================
           INSERT INVOICE
        ========================== */
        $stmt = $mysqli->prepare("
            INSERT INTO invoices (
                company_id, invoice,
                invoice_date, invoice_due_date,
                subtotal, shipping, discount, vat, total,
                created_by, notes, invoice_type, status
            ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)
        ");

        $stmt->bind_param(
            "issssddddssss",
            $company_id,
            $finalInvoice,
            $invoice_date,
            $invoice_due_date,
            $subtotal,
            $shipping,
            $discount,
            $vat,
            $total,
            $_POST['created_by'],
            $_POST['invoice_notes'],
            $_POST['invoice_type'],
            $_POST['invoice_status']
        );

        $stmt->execute();

        /* =========================
           INSERT CUSTOMER
        ========================== */
        $cust = $mysqli->prepare("
            INSERT INTO customers (
                company_id, invoice,
                name, email, address_1, address_2,
                town, county, postcode, phone,
                name_ship, address_1_ship, address_2_ship,
                town_ship, county_ship, postcode_ship
            ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
        ");

        $cust->bind_param(
            "isssssssssssssss",
            $company_id,
            $finalInvoice,
            $_POST['customer_name'],
            $_POST['customer_email'],
            $_POST['customer_address_1'],
            $_POST['customer_address_2'],
            $_POST['customer_town'],
            $_POST['customer_county'],
            $_POST['customer_postcode'],
            $_POST['customer_phone'],
            $_POST['customer_name_ship'],
            $_POST['customer_address_1_ship'],
            $_POST['customer_address_2_ship'],
            $_POST['customer_town_ship'],
            $_POST['customer_county_ship'],
            $_POST['customer_postcode_ship']
        );

        $cust->execute();

        /* =========================
           INSERT ITEMS
        ========================== */
        $itemStmt = $mysqli->prepare("
            INSERT INTO invoice_items (
                company_id, invoice,
                product, product_description,
                qty, price, discount, subtotal, item_order
            ) VALUES (?,?,?,?,?,?,?,?,?)
        ");

        foreach ($_POST['invoice_product'] as $i => $product) {

            if (trim($product) === '') continue;

            $qty      = (float) $_POST['invoice_product_qty'][$i];
            $price    = (float) $_POST['invoice_product_price'][$i];
            $disc     = (float) ($_POST['invoice_product_discount'][$i] ?? 0);
            $sub      = (float) $_POST['invoice_product_sub'][$i];

            $itemStmt->bind_param(
                "isssddddi",
                $company_id,
                $finalInvoice,
                $product,
                $_POST['invoice_product_description'][$i],
                $qty,
                $price,
                $disc,
                $sub,
                $i
            );

            $itemStmt->execute();
        }

        $mysqli->commit();

        echo json_encode([
            'status'  => 'success',
            'message' => 'Invoice created successfully',
			'invoice' => $finalInvoice
        ]);

		

    } catch (Throwable $e) {

        $mysqli->rollback();

        echo json_encode([
            'status'  => 'error',
            'message' => $e->getMessage()
        ]);
    }

    $mysqli->close();
    exit;
}


// delete invoice
if ($action === 'delete_invoice') {

    header('Content-Type: application/json');
    session_start();

    if (!isset($_SESSION['company_id'])) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Company context missing. Please re-login.'
        ]);
        exit;
    }

    $company_id = (int) $_SESSION['company_id'];

    if ($mysqli->connect_error) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Database connection failed'
        ]);
        exit;
    }

    if (empty($_POST['delete'])) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Invalid invoice reference'
        ]);
        exit;
    }

    $invoice = trim($_POST['delete']); // invoice number (string)

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

    try {

        $mysqli->begin_transaction();

        /* =========================
           DELETE INVOICE ITEMS
        ========================== */
        $stmt1 = $mysqli->prepare("
            DELETE FROM invoice_items
            WHERE invoice = ?
              AND company_id = ?
        ");
        $stmt1->bind_param("si", $invoice, $company_id);
        $stmt1->execute();

        /* =========================
           DELETE CUSTOMER RECORD
        ========================== */
        $stmt2 = $mysqli->prepare("
            DELETE FROM customers
            WHERE invoice = ?
              AND company_id = ?
        ");
        $stmt2->bind_param("si", $invoice, $company_id);
        $stmt2->execute();

        /* =========================
           DELETE INVOICE
        ========================== */
        $stmt3 = $mysqli->prepare("
            DELETE FROM invoices
            WHERE invoice = ?
              AND company_id = ?
        ");
        $stmt3->bind_param("si", $invoice, $company_id);
        $stmt3->execute();

        if ($stmt3->affected_rows === 0) {
            throw new Exception("Invoice not found or access denied");
        }

        $mysqli->commit();

        echo json_encode([
            'status'  => 'Success',
            'message' => 'Invoice deleted successfully'
        ]);

    } catch (Throwable $e) {

        $mysqli->rollback();

        echo json_encode([
            'status'  => 'Error',
            'message' => $e->getMessage()
        ]);
    }

    $mysqli->close();
    exit;
}

// delete voucher
if ($action === 'delete_voucher') {

    header('Content-Type: application/json');
    session_start();

    if (!isset($_SESSION['company_id'])) {
        echo json_encode([
            'status'  => 'error',
            'message' => 'Company context missing. Please re-login.'
        ]);
        exit;
    }

    $company_id = (int) $_SESSION['company_id'];

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

    try {

        if (empty($_POST['voucher_id'])) {
            throw new Exception("Invalid voucher reference");
        }

        // voucher_id is STRING (e.g EXP-00045)
        $voucher_id = trim($_POST['voucher_id']);

        $mysqli->begin_transaction();

        /* =========================
           DELETE VOUCHER ITEMS
        ========================== */
        $stmt1 = $mysqli->prepare("
            DELETE FROM voucher_items
            WHERE invoice = ?
              AND company_id = ?
        ");
        $stmt1->bind_param("si", $voucher_id, $company_id);
        $stmt1->execute();

        /* =========================
           DELETE VOUCHER
        ========================== */
        $stmt2 = $mysqli->prepare("
            DELETE FROM vouchers
            WHERE voucher_id = ?
              AND company_id = ?
        ");
        $stmt2->bind_param("si", $voucher_id, $company_id);
        $stmt2->execute();

        if ($stmt2->affected_rows === 0) {
            throw new Exception("Voucher not found or access denied");
        }

        $mysqli->commit();

        echo json_encode([
            'status'  => 'success',
            'message' => 'Voucher deleted successfully'
        ]);

    } catch (Throwable $e) {

        $mysqli->rollback();

        echo json_encode([
            'status'  => 'error',
            'message' => $e->getMessage()
        ]);
    }

    exit;
}



// Update Customer
if ($action === 'update_customer') {

    header('Content-Type: application/json');
    session_start();

    /* =========================
       COMPANY CONTEXT
    ========================== */
    if (empty($_SESSION['company_id'])) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Company context missing. Please re-login.'
        ]);
        exit;
    }

    $company_id = (int) $_SESSION['company_id'];

    /* =========================
       BASIC VALIDATION
    ========================== */
    if (empty($_POST['id']) || empty($_POST['customer_name'])) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Invalid customer data supplied.'
        ]);
        exit;
    }

    $customer_id = (int) $_POST['id'];

    /* =========================
       BILLING INFO
    ========================== */
    $customer_name      = trim($_POST['customer_name']);
    $customer_email     = trim($_POST['customer_email'] ?? '');
    $customer_address_1 = trim($_POST['customer_address_1'] ?? '');
    $customer_address_2 = trim($_POST['customer_address_2'] ?? '');
    $customer_town      = trim($_POST['customer_town'] ?? '');
    $customer_county    = trim($_POST['customer_county'] ?? '');
    $customer_postcode  = trim($_POST['customer_postcode'] ?? '');
    $customer_phone     = trim($_POST['customer_phone'] ?? '');

    /* =========================
       SHIPPING INFO
    ========================== */
    $customer_name_ship      = trim($_POST['customer_name_ship'] ?? '');
    $customer_address_1_ship = trim($_POST['customer_address_1_ship'] ?? '');
    $customer_address_2_ship = trim($_POST['customer_address_2_ship'] ?? '');
    $customer_town_ship      = trim($_POST['customer_town_ship'] ?? '');
    $customer_county_ship    = trim($_POST['customer_county_ship'] ?? '');
    $customer_postcode_ship  = trim($_POST['customer_postcode_ship'] ?? '');

    /* =========================
       UPDATE CUSTOMER (SAFE)
    ========================== */
    $stmt = $mysqli->prepare("
        UPDATE store_customers SET
            name = ?,
            email = ?,
            address_1 = ?,
            address_2 = ?,
            town = ?,
            county = ?,
            postcode = ?,
            phone = ?,
            name_ship = ?,
            address_1_ship = ?,
            address_2_ship = ?,
            town_ship = ?,
            county_ship = ?,
            postcode_ship = ?
        WHERE id = ?
          AND company_id = ?
    ");

    if (!$stmt) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Database prepare failed.'
        ]);
        exit;
    }

    $stmt->bind_param(
        'ssssssssssssssii',
        $customer_name,
        $customer_email,
        $customer_address_1,
        $customer_address_2,
        $customer_town,
        $customer_county,
        $customer_postcode,
        $customer_phone,
        $customer_name_ship,
        $customer_address_1_ship,
        $customer_address_2_ship,
        $customer_town_ship,
        $customer_county_ship,
        $customer_postcode_ship,
        $customer_id,
        $company_id
    );

    $stmt->execute();

    if ($stmt->affected_rows === 0) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Customer not found or access denied.'
        ]);
    } else {
        echo json_encode([
            'status'  => 'Success',
            'message' => 'Customer updated successfully.'
        ]);
    }

    $stmt->close();
    $mysqli->close();
    exit;
}



// update invoice
if ($action === 'update_invoice') {

    header('Content-Type: application/json');
    session_start();

    if (!isset($_SESSION['company_id'])) {
        echo json_encode([
            "status"  => "Error",
            "message" => "Company context missing. Please re-login."
        ]);
        exit;
    }

    $company_id = (int) $_SESSION['company_id'];

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

    try {
        $mysqli->begin_transaction();

        /* =========================
           BASIC INPUTS
        ========================== */
        $invoice_number   = trim($_POST['invoice_id']);
        $invoice_date     = $_POST['invoice_date'];
        $invoice_due_date = $_POST['invoice_due_date'];
        $custom_email     = $_POST['custom_email'] ?? '';
        $created_by       = $_POST['created_by'];
        $invoice_notes    = $_POST['invoice_notes'];
        $invoice_type     = $_POST['invoice_type'];
        $invoice_status   = $_POST['invoice_status'];

        $subtotal  = (float) $_POST['invoice_subtotal'];
        $shipping  = (float) $_POST['invoice_shipping'];
        $discount  = (float) $_POST['invoicediscount'];
        $vat       = (float) $_POST['invoice_vat'];
        $total     = (float) $_POST['invoice_total'];

        /* =========================
           UPDATE INVOICE
        ========================== */
        $stmt = $mysqli->prepare("
            UPDATE invoices SET
                custom_email = ?,
                invoice_date = ?,
                invoice_due_date = ?,
                subtotal = ?,
                shipping = ?,
                discount = ?,
                vat = ?,
                total = ?,
                created_by = ?,
                notes = ?,
                invoice_type = ?,
                status = ?
            WHERE invoice = ?
              AND company_id = ?
        ");

        $stmt->bind_param(
            "sssdddddsssssi",
            $custom_email,
            $invoice_date,
            $invoice_due_date,
            $subtotal,
            $shipping,
            $discount,
            $vat,
            $total,
            $created_by,
            $invoice_notes,
            $invoice_type,
            $invoice_status,
            $invoice_number,
            $company_id
        );

        $stmt->execute();

        if ($stmt->affected_rows === 0) {
            throw new Exception("Invoice not found or access denied");
        }

        /* =========================
           UPDATE CUSTOMER
        ========================== */
        $cust = $mysqli->prepare("
            UPDATE customers SET
                name = ?, email = ?, address_1 = ?, address_2 = ?,
                town = ?, county = ?, postcode = ?, phone = ?,
                name_ship = ?, address_1_ship = ?, address_2_ship = ?,
                town_ship = ?, county_ship = ?, postcode_ship = ?
            WHERE invoice = ?
              AND company_id = ?
        ");

        $cust->bind_param(
            "sssssssssssssssi",
            $_POST['customer_name'],
            $_POST['customer_email'],
            $_POST['customer_address_1'],
            $_POST['customer_address_2'],
            $_POST['customer_town'],
            $_POST['customer_county'],
            $_POST['customer_postcode'],
            $_POST['customer_phone'],
            $_POST['customer_name_ship'],
            $_POST['customer_address_1_ship'],
            $_POST['customer_address_2_ship'],
            $_POST['customer_town_ship'],
            $_POST['customer_county_ship'],
            $_POST['customer_postcode_ship'],
            $invoice_number,
            $company_id
        );

        $cust->execute();

        /* =========================
           REPLACE INVOICE ITEMS
        ========================== */
        $del = $mysqli->prepare("
            DELETE FROM invoice_items
            WHERE invoice = ?
              AND company_id = ?
        ");
        $del->bind_param("si", $invoice_number, $company_id);
        $del->execute();

        $itemStmt = $mysqli->prepare("
            INSERT INTO invoice_items (
                company_id,
                invoice,
                product,
                product_description,
                qty,
                price,
                discount,
                subtotal,
                item_order
            ) VALUES (?,?,?,?,?,?,?,?,?)
        ");

        foreach ($_POST['invoice_product'] as $i => $product) {

            if (trim($product) === '') continue;

            $qty      = (float) $_POST['invoice_product_qty'][$i];
            $price    = (float) $_POST['invoice_product_price'][$i];
            $disc     = (float) ($_POST['invoice_product_discount'][$i] ?? 0);
            $sub      = ($qty * $price) - $disc;

            $itemStmt->bind_param(
                "isssddddi",
                $company_id,
                $invoice_number,
                $product,
                $_POST['invoice_product_description'][$i],
                $qty,
                $price,
                $disc,
                $sub,
                $i
            );

            $itemStmt->execute();
        }

        $mysqli->commit();

        echo json_encode([
            "status"  => "Success",
            "message" => "Invoice updated successfully!"
        ]);

    } catch (Throwable $e) {

        $mysqli->rollback();

        echo json_encode([
            "status"  => "Error",
            "message" => $e->getMessage()
        ]);
    }

    exit;
}





// Adding new product
if ($action === 'add_product') {

    header('Content-Type: application/json');
    session_start();

    if (!isset($_SESSION['company_id'])) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Company context missing. Please re-login.'
        ]);
        exit;
    }

    $company_id = (int) $_SESSION['company_id'];

    if ($mysqli->connect_error) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Database connection failed'
        ]);
        exit;
    }

    // Sanitize & validate input
    $product_name  = trim($_POST['product_name'] ?? '');
    $product_desc  = trim($_POST['product_desc'] ?? '');
    $product_price = isset($_POST['product_price'])
        ? (float) $_POST['product_price']
        : 0.00;

    if ($product_name === '' || $product_price <= 0) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Product name and valid price are required'
        ]);
        exit;
    }

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

    try {

        $stmt = $mysqli->prepare("
            INSERT INTO products (
                company_id,
                product_name,
                product_desc,
                product_price
            ) VALUES (?, ?, ?, ?)
        ");

        $stmt->bind_param(
            "issd",
            $company_id,
            $product_name,
            $product_desc,
            $product_price
        );

        $stmt->execute();

        echo json_encode([
            'status'  => 'Success',
            'message' => 'Product has been added successfully!'
        ]);

    } catch (Throwable $e) {

        echo json_encode([
            'status'  => 'Error',
            'message' => $e->getMessage()
        ]);
    }

    $mysqli->close();
    exit;
}

// Update product
if ($action === 'update_product') {

    header('Content-Type: application/json');
    session_start();

    if (!isset($_SESSION['company_id'])) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Company context missing. Please re-login.'
        ]);
        exit;
    }

    $company_id = (int) $_SESSION['company_id'];

    if ($mysqli->connect_error) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Database connection failed'
        ]);
        exit;
    }

    // Sanitize & validate input
    $product_id    = isset($_POST['id']) ? (int) $_POST['id'] : 0;
    $product_name  = trim($_POST['product_name'] ?? '');
    $product_desc  = trim($_POST['product_desc'] ?? '');
    $product_price = isset($_POST['product_price'])
        ? (float) $_POST['product_price']
        : 0.00;

    if ($product_id <= 0 || $product_name === '' || $product_price <= 0) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Invalid product data supplied'
        ]);
        exit;
    }

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

    try {

        $stmt = $mysqli->prepare("
            UPDATE products
            SET
                product_name  = ?,
                product_desc  = ?,
                product_price = ?
            WHERE product_id = ?
              AND company_id = ?
        ");

        $stmt->bind_param(
            "ssdii",
            $product_name,
            $product_desc,
            $product_price,
            $product_id,
            $company_id
        );

        $stmt->execute();

        if ($stmt->affected_rows === 0) {
            throw new Exception('Product not found or access denied');
        }

        echo json_encode([
            'status'  => 'Success',
            'message' => 'Product has been updated successfully!'
        ]);

    } catch (Throwable $e) {

        echo json_encode([
            'status'  => 'Error',
            'message' => $e->getMessage()
        ]);
    }

    $mysqli->close();
    exit;
}


// Delete product
if ($action === 'delete_product') {

    header('Content-Type: application/json');
    session_start();

    if (!isset($_SESSION['company_id'])) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Company context missing. Please re-login.'
        ]);
        exit;
    }

    $company_id = (int) $_SESSION['company_id'];

    if ($mysqli->connect_error) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Database connection failed'
        ]);
        exit;
    }

    $product_id = isset($_POST['delete']) ? (int) $_POST['delete'] : 0;

    if ($product_id <= 0) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Invalid product ID'
        ]);
        exit;
    }

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

    try {

        $stmt = $mysqli->prepare("
            DELETE FROM products
            WHERE product_id = ?
              AND company_id = ?
        ");

        $stmt->bind_param("ii", $product_id, $company_id);
        $stmt->execute();

        if ($stmt->affected_rows === 0) {
            throw new Exception('Product not found or access denied');
        }

        echo json_encode([
            'status'  => 'Success',
            'message' => 'Product has been deleted successfully!'
        ]);

    } catch (Throwable $e) {

        echo json_encode([
            'status'  => 'Error',
            'message' => $e->getMessage()
        ]);
    }

    $mysqli->close();
    exit;
}



// Adding new user
if($action == 'add_user') {

	$user_name = $_POST['name'];
	$user_username = $_POST['username'];
	$user_email = $_POST['email'];
	$user_phone = $_POST['phone'];
	$user_password = $_POST['password'];
	$role = $_POST['role'];

	//our insert query query
	$query  = "INSERT INTO users
				(
					name,
					username,
					email,
					phone,
					password,
					role
				)
				VALUES (
					?,
					?, 
                	?,
                	?,
					?,
                	?
                );
              ";

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

	/* Prepare statement */
	$stmt = $mysqli->prepare($query);
	if($stmt === false) {
	  trigger_error('Wrong SQL: ' . $query . ' Error: ' . $mysqli->error, E_USER_ERROR);
	}

	$user_password = md5($user_password);
	/* Bind parameters. TYpes: s = string, i = integer, d = double,  b = blob */
	$stmt->bind_param('ssssss',$user_name,$user_username,$user_email,$user_phone,$user_password,$role);

	if($stmt->execute()){
	    //if saving success
		echo json_encode(array(
			'status' => 'Success',
			'message'=> 'User has been added successfully!'
		));

	} else {
	    //if unable to create new record
	    echo json_encode(array(
	    	'status' => 'Error',
	    	//'message'=> 'There has been an error, please try again.'
	    	'message' => 'There has been an error, please try again.<pre>'.$mysqli->error.'</pre><pre>'.$query.'</pre>'
	    ));
	}

	//close database connection
	$mysqli->close();
}

// Update user
if($action == 'update_user') {

	// output any connection error
	if ($mysqli->connect_error) {
	    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
	}

	// user information
	$getID = $_POST['id']; // id
	$name = $_POST['name']; // name
	$username = $_POST['username']; // username
	$email = $_POST['email']; // email
	$phone = $_POST['phone']; // phone
	$password = $_POST['password']; // password
	$role = $_POST['role']; // password

	if($password == ''){
		// the query
		$query = "UPDATE users SET
					name = ?,
					username = ?,
					email = ?,
					phone = ?,
					role = ?
				 WHERE id = ?
				";
	} else {
		// the query
		$query = "UPDATE users SET
					name = ?,
					username = ?,
					email = ?,
					phone = ?,
					password = ?,
					role = ?
				 WHERE id = ?
				";
	}

	/* Prepare statement */
	$stmt = $mysqli->prepare($query);
	if($stmt === false) {
	  trigger_error('Wrong SQL: ' . $query . ' Error: ' . $mysqli->error, E_USER_ERROR);
	}

	if($password == ''){
		/* Bind parameters. TYpes: s = string, i = integer, d = double,  b = blob */
		$stmt->bind_param(
			'ssssss',
			$name,$username,$email,$phone,$role,$getID
		);
	} else {
		$password = md5($password);
		/* Bind parameters. TYpes: s = string, i = integer, d = double,  b = blob */
		$stmt->bind_param(
			'sssssss',
			$name,$username,$email,$phone,$password,$role,$getID
		);
	}

	//execute the query
	if($stmt->execute()){
	    //if saving success
		echo json_encode(array(
			'status' => 'Success',
			'message'=> 'User has been updated successfully!'
		));

	} else {
	    //if unable to create new record
	    echo json_encode(array(
	    	'status' => 'Error',
	    	//'message'=> 'There has been an error, please try again.'
	    	'message' => 'There has been an error, please try again.<pre>'.$mysqli->error.'</pre><pre>'.$query.'</pre>'
	    ));
	}

	//close database connection
	$mysqli->close();
	
}

// Delete User
if($action == 'delete_user') {

	// output any connection error
	if ($mysqli->connect_error) {
	    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
	}

	$id = $_POST["delete"];

	// the query
	$query = "DELETE FROM users WHERE id = ?";

	/* Prepare statement */
	$stmt = $mysqli->prepare($query);
	if($stmt === false) {
	  trigger_error('Wrong SQL: ' . $query . ' Error: ' . $mysqli->error, E_USER_ERROR);
	}

	/* Bind parameters. TYpes: s = string, i = integer, d = double,  b = blob */
	$stmt->bind_param('s',$id);

	if($stmt->execute()){
	    //if saving success
		echo json_encode(array(
			'status' => 'Success',
			'message'=> 'User has been deleted successfully!'
		));

	} else {
	    //if unable to create new record
	    echo json_encode(array(
	    	'status' => 'Error',
	    	//'message'=> 'There has been an error, please try again.'
	    	'message' => 'There has been an error, please try again.<pre>'.$mysqli->error.'</pre><pre>'.$query.'</pre>'
	    ));
	}

	// close connection 
	$mysqli->close();

}

// Delete customer
if ($action === 'delete_customer') {

    header('Content-Type: application/json');
    session_start();

    /* =========================
       COMPANY CONTEXT CHECK
    ========================== */
    if (empty($_SESSION['company_id'])) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Company context missing. Please re-login.'
        ]);
        exit;
    }

    $company_id = (int) $_SESSION['company_id'];

    /* =========================
       BASIC VALIDATION
    ========================== */
    if (empty($_POST['delete'])) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Invalid customer reference.'
        ]);
        exit;
    }

    $customer_id = (int) $_POST['delete'];

    /* =========================
       DELETE (COMPANY-SAFE)
    ========================== */
    $stmt = $mysqli->prepare("
        DELETE FROM store_customers
        WHERE id = ?
          AND company_id = ?
    ");

    if (!$stmt) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Database prepare failed.'
        ]);
        exit;
    }

    $stmt->bind_param('ii', $customer_id, $company_id);
    $stmt->execute();

    if ($stmt->affected_rows === 0) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Customer not found or access denied.'
        ]);
    } else {
        echo json_encode([
            'status'  => 'Success',
            'message' => 'Customer deleted successfully.'
        ]);
    }

    $stmt->close();
    $mysqli->close();
    exit;
}

// Delete expenses
if($action == 'delete_expense') {

	// output any connection error
	if ($mysqli->connect_error) {
	    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
	}

	$id = $_POST["delete"];

	// the query
	$query = "DELETE FROM expenses WHERE id = ?";

	/* Prepare statement */
	$stmt = $mysqli->prepare($query);
	if($stmt === false) {
	  trigger_error('Wrong SQL: ' . $query . ' Error: ' . $mysqli->error, E_USER_ERROR);
	}

	/* Bind parameters. TYpes: s = string, i = integer, d = double,  b = blob */
	$stmt->bind_param('s',$id);

	if($stmt->execute()){
	    //if saving success
		echo json_encode(array(
			'status' => 'Success',
			'message'=> 'Expenses has been deleted successfully!'
		));

	} else {
	    //if unable to create new record
	    echo json_encode(array(
	    	'status' => 'Error',
	    	//'message'=> 'There has been an error, please try again.'
	    	'message' => 'There has been an error, please try again.<pre>'.$mysqli->error.'</pre><pre>'.$query.'</pre>'
	    ));
	}

	// close connection 
	$mysqli->close();

}




// Create Transaction / Expense
if ($action === 'add_expense') {

    function syncTransactionCounter(mysqli $mysqli, int $company_id, int $usedNumber): void
    {
        $stmt = $mysqli->prepare("
            UPDATE company
            SET transaction_counter = GREATEST(transaction_counter, ?)
            WHERE id = ?
        ");
        $stmt->bind_param("ii", $usedNumber, $company_id);
        $stmt->execute();
    }

    header('Content-Type: application/json');
    session_start();

    /* =========================
       COMPANY CONTEXT
    ========================== */
    if (!isset($_SESSION['company_id'])) {
        echo json_encode([
            'status'  => 'error',
            'message' => 'Company context missing. Please re-login.'
        ]);
        exit;
    }

    $company_id = (int) $_SESSION['company_id'];

    /* =========================
       DB CONNECTION
    ========================== */
    $mysqli = new mysqli(DATABASE_HOST, DATABASE_USER, DATABASE_PASS, DATABASE_NAME);
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

    try {

        $mysqli->begin_transaction();

        /* =========================
           NUMBER LOGIC (EXACT PATTERN)
        ========================== */
        $userTransaction    = trim($_POST['expense_id'] ?? '');
        $previewTransaction = trim($_POST['preview_transaction_number'] ?? '');

        if ($userTransaction === $previewTransaction) {
            // User accepted preview → atomic increment
            $finalTransaction = reserveTransactionNumber($mysqli, $company_id);
        } else {
            if ($userTransaction !== '') {
                $finalTransaction = (int) $userTransaction;

                // Keep counter in sync
                syncTransactionCounter(
                    $mysqli,
                    $company_id,
                    $finalTransaction + 1
                );
            } else {
                $finalTransaction = reserveTransactionNumber($mysqli, $company_id);
            }
        }

        /* =========================
           FILE UPLOAD
        ========================== */
        $expense_doc = null;

        if (isset($_FILES['expense_doc']) && $_FILES['expense_doc']['error'] === 0) {

            $allowed_ext = ['pdf', 'doc', 'docx', 'jpg', 'jpeg', 'png'];
            $target_dir  = "images/doc/";

            if (!is_dir($target_dir)) {
                mkdir($target_dir, 0777, true);
            }

            $file_ext = strtolower(pathinfo(
                $_FILES['expense_doc']['name'],
                PATHINFO_EXTENSION
            ));

            if (!in_array($file_ext, $allowed_ext)) {
                throw new Exception("Invalid file type");
            }

            $expense_doc = "EXP_" . time() . "_" . random_int(1000, 9999) . "." . $file_ext;

            if (!move_uploaded_file(
                $_FILES['expense_doc']['tmp_name'],
                $target_dir . $expense_doc
            )) {
                throw new Exception("File upload failed");
            }
        }

		$expense_amount = (float) ($_POST['expense_amount'] ?? 0);
        /* =========================
           INSERT EXPENSE
        ========================== */
        $stmt = $mysqli->prepare("
            INSERT INTO expenses (
                company_id,
                expense_id,
                expense_date,
                transaction_type,
                expense_desc,
                expense_amount,
                authorised_by,
                created_by,
                reference_no,
                authorised_by2,
                transaction_status,
                transaction_mode,
                expense_doc
            ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)
        ");

        $stmt->bind_param(
            "issssdsssssss",
            $company_id,
            $finalTransaction,
            $_POST['expense_date'],
            $_POST['transaction_type'],
            $_POST['expense_desc'],
            $expense_amount,  
            $_POST['authorised_by'],
            $_POST['created_by'],
            $_POST['reference_no'],
            $_POST['authorised_by2'],
            $_POST['transaction_status'],
            $_POST['transaction_mode'],
            $expense_doc
        );

        $stmt->execute();

        $mysqli->commit();

        echo json_encode([
            'status'      => 'success',
            'message'     => 'Transaction added successfully',
            'transaction' => $finalTransaction
        ]);

    } catch (Throwable $e) {

        $mysqli->rollback();

        echo json_encode([
            'status'  => 'error',
            'message' => $e->getMessage()
        ]);
    }

    $mysqli->close();
    exit;
}

// Update Expense
if ($action === 'update_expense') {

    header('Content-Type: application/json');
    session_start();

    /* =========================
       COMPANY CONTEXT CHECK
    ========================== */
    if (!isset($_SESSION['company_id'])) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Company context missing. Please re-login.'
        ]);
        exit;
    }

    $company_id = (int) $_SESSION['company_id'];

    /* =========================
       FETCH POST FIELDS
    ========================== */
    $id                 = (int) ($_POST['id'] ?? 0);
    $expense_id         = $_POST['expense_id'] ?? '';
    $expense_date       = $_POST['expense_date'] ?? '';
    $transaction_type   = $_POST['transaction_type'] ?? '';
    $expense_desc       = $_POST['expense_desc'] ?? '';
    $expense_amount     = (float) ($_POST['expense_amount'] ?? 0);
    $authorised_by      = $_POST['authorised_by'] ?? '';
    $created_by         = $_POST['created_by'] ?? '';

    $reference_no       = $_POST['reference_no'] ?? '';
    $authorised_by2     = $_POST['authorised_by2'] ?? '';
    $transaction_status = $_POST['transaction_status'] ?? '';
    $transaction_mode   = $_POST['transaction_mode'] ?? '';

    /* =========================
       FILE UPLOAD (OPTIONAL)
    ========================== */
    $expense_doc = null;

    if (isset($_FILES['expense_doc']) && $_FILES['expense_doc']['error'] === 0) {

        $allowed_ext = ['pdf', 'doc', 'docx', 'jpg', 'jpeg', 'png'];
        $target_dir  = "images/doc/";

        if (!is_dir($target_dir)) {
            mkdir($target_dir, 0777, true);
        }

        $file_tmp = $_FILES['expense_doc']['tmp_name'];
        $file_ext = strtolower(pathinfo($_FILES['expense_doc']['name'], PATHINFO_EXTENSION));

        if (!in_array($file_ext, $allowed_ext)) {
            echo json_encode([
                'status'  => 'Error',
                'message' => 'Invalid file type.'
            ]);
            exit;
        }

        $expense_doc = "EXP_" . time() . "_" . random_int(1000, 9999) . "." . $file_ext;

        if (!move_uploaded_file($file_tmp, $target_dir . $expense_doc)) {
            echo json_encode([
                'status'  => 'Error',
                'message' => 'File upload failed.'
            ]);
            exit;
        }
    }

    /* =========================
       UPDATE QUERY
    ========================== */
    $sql = "
        UPDATE expenses SET
            expense_id = ?,
            expense_date = ?,
            transaction_type = ?,
            expense_desc = ?,
            expense_amount = ?,
            authorised_by = ?,
            created_by = ?,
            reference_no = ?,
            authorised_by2 = ?,
            transaction_status = ?,
            transaction_mode = ?
            " . ($expense_doc ? ", expense_doc = ?" : "") . "
        WHERE id = ?
          AND company_id = ?
    ";

    $stmt = $mysqli->prepare($sql);

    if (!$stmt) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'SQL prepare failed'
        ]);
        exit;
    }

    /* =========================
       BIND PARAMS DYNAMICALLY
    ========================== */
    if ($expense_doc) {
        $stmt->bind_param(
            "ssssdsissssssi",
            $expense_id,
            $expense_date,
            $transaction_type,
            $expense_desc,
            $expense_amount,
            $authorised_by,
            $created_by,
            $reference_no,
            $authorised_by2,
            $transaction_status,
            $transaction_mode,
            $expense_doc,
            $id,
            $company_id
        );
    } else {
        $stmt->bind_param(
            "ssssdssssssii",
            $expense_id,
            $expense_date,
            $transaction_type,
            $expense_desc,
            $expense_amount,
            $authorised_by,
            $created_by,
            $reference_no,
            $authorised_by2,
            $transaction_status,
            $transaction_mode,
            $id,
            $company_id
        );
    }

    /* =========================
       EXECUTE
    ========================== */
    if ($stmt->execute() && $stmt->affected_rows > 0) {
        echo json_encode([
            'status'  => 'Success',
            'message' => 'Expense updated successfully!'
        ]);
    } else {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Expense not found or access denied.'
        ]);
    }

    $stmt->close();
    $mysqli->close();
}




// Adding new Schedule
if ($action === 'add_schedule') {

    header('Content-Type: application/json');
    session_start();

    // Ensure company context exists
    if (!isset($_SESSION['company_id'])) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Company context missing. Please re-login.'
        ]);
        exit;
    }

    $company_id = (int) $_SESSION['company_id'];

    // Fetch inputs safely
    $end              = $_POST['end'] ?? null;
    $schedule_type    = $_POST['schedule_type'] ?? '';
    $title            = $_POST['title'] ?? '';
    $description      = $_POST['description'] ?? '';
    $start            = $_POST['start'] ?? null;
    $schedule_amount  = $_POST['schedule_amount'] ?? 0;
    $client_location  = $_POST['client_location'] ?? '';

    // Basic validation
    if ($title === '' || $start === '') {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Title and start date are required.'
        ]);
        exit;
    }

    // Insert query (company-aware)
    $query = "
        INSERT INTO event_calendar (
            company_id,
            end,
            schedule_type,
            title,
            description,
            start,
            schedule_amount,
            client_location
        ) VALUES (
            ?, ?, ?, ?, ?, ?, ?, ?
        )
    ";

    $stmt = $mysqli->prepare($query);
    if ($stmt === false) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Database prepare failed'
        ]);
        exit;
    }

    $stmt->bind_param(
        'isssssss',
        $company_id,
        $end,
        $schedule_type,
        $title,
        $description,
        $start,
        $schedule_amount,
        $client_location
    );

    if ($stmt->execute()) {
        echo json_encode([
            'status'  => 'Success',
            'message' => 'Schedule has been added successfully!'
        ]);
    } else {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Unable to add schedule. Please try again.'
        ]);
    }

    $stmt->close();
    $mysqli->close();
}

// Update Schedule
if ($action === 'update_schedule') {

    header('Content-Type: application/json');
    session_start();

    // Ensure company context exists
    if (!isset($_SESSION['company_id'])) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Company context missing. Please re-login.'
        ]);
        exit;
    }

    $company_id = (int) $_SESSION['company_id'];

    // Output any connection error
    if ($mysqli->connect_error) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Database connection failed'
        ]);
        exit;
    }

    // Fetch inputs safely
    $id               = (int) ($_POST['id'] ?? 0);
    $schedule_type    = $_POST['schedule_type'] ?? '';
    $title            = $_POST['title'] ?? '';
    $description      = $_POST['description'] ?? '';
    $start            = $_POST['start'] ?? null;
    $schedule_amount  = $_POST['schedule_amount'] ?? 0;
    $client_location  = $_POST['client_location'] ?? '';

    // Basic validation
    if ($id === 0 || $title === '' || $start === null) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Invalid schedule data supplied.'
        ]);
        exit;
    }

    // Company-safe update query
    $query = "
        UPDATE event_calendar SET
            schedule_type   = ?,
            title           = ?,
            description     = ?,
            start           = ?,
            schedule_amount = ?,
            client_location = ?
        WHERE id = ?
          AND company_id = ?
    ";

    $stmt = $mysqli->prepare($query);
    if ($stmt === false) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Database prepare failed'
        ]);
        exit;
    }

    $stmt->bind_param(
        'ssssdsii',
        $schedule_type,
        $title,
        $description,
        $start,
        $schedule_amount,
        $client_location,
        $id,
        $company_id
    );

    if ($stmt->execute()) {

        if ($stmt->affected_rows === 0) {
            echo json_encode([
                'status'  => 'Error',
                'message' => 'Schedule not found or access denied.'
            ]);
        } else {
            echo json_encode([
                'status'  => 'Success',
                'message' => 'Schedule has been updated successfully!'
            ]);
        }

    } else {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Unable to update schedule.'
        ]);
    }

    $stmt->close();
    $mysqli->close();
}



// Delete Schedule
if ($action === 'delete_schedule') {

    header('Content-Type: application/json');
    session_start();

    // Ensure company context
    if (!isset($_SESSION['company_id'])) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Company context missing. Please re-login.'
        ]);
        exit;
    }

    $company_id = (int) $_SESSION['company_id'];

    // Validate ID
    if (empty($_POST['delete'])) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Invalid schedule reference.'
        ]);
        exit;
    }

    $schedule_id = (int) $_POST['delete'];

    // DB connection check
    if ($mysqli->connect_error) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Database connection failed'
        ]);
        exit;
    }

    // Delete (company-safe)
    $query = "
        DELETE FROM event_calendar
        WHERE id = ?
          AND company_id = ?
        LIMIT 1
    ";

    $stmt = $mysqli->prepare($query);
    if ($stmt === false) {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Database prepare failed'
        ]);
        exit;
    }

    $stmt->bind_param("ii", $schedule_id, $company_id);
    $stmt->execute();

    if ($stmt->affected_rows === 1) {
        echo json_encode([
            'status'  => 'Success',
            'message' => 'Schedule has been deleted successfully!'
        ]);
    } else {
        echo json_encode([
            'status'  => 'Error',
            'message' => 'Schedule not found or access denied.'
        ]);
    }

    $stmt->close();
    $mysqli->close();
    exit;
}

?>