<?php

require_once __DIR__ . '/../src/session.php';

// Redirect to login if not authenticated
if (!isAuthenticated()) {
    header("Location: login.php");
    exit;
}


ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../src/config.php';
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/helpers.php';
require_once __DIR__ . '/../vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\IOFactory;

// Current business context
$current_business = getCurrentBusiness();
$business_id = (int)($current_business['business_id'] ?? 0);

function recalc_order_totals($order_id) {
    $order = one("SELECT discount FROM orders WHERE id=?", [$order_id]);
    $discount = (float)($order['discount'] ?? 0);

    $settings = one("SELECT gst_applicable, gst_rate FROM settings WHERE id=?", [$GLOBALS['business_id']]);
    $gst_enabled = (int)($settings['gst_applicable'] ?? 0);
    $gst_rate    = (float)($settings['gst_rate'] ?? 0);

    $ois = all_rows("SELECT * FROM order_items WHERE order_id=?", [$order_id]);
    $subtotal = 0.0;
    foreach ($ois as $oi) {
        $subtotal += $oi['price'] * $oi['qty'];
    }
    $taxable = max(0.0, $subtotal - $discount);
    $tax = 0.0;
    if ($gst_enabled && $gst_rate > 0) {
        $tax = round($taxable * ($gst_rate / 100.0), 2);
    }
    $total = round($taxable + $tax, 2);
    query("UPDATE orders 
              SET subtotal=?, discount=?, tax=?, total=? 
            WHERE id=?",
        [$subtotal, $discount, $tax, $total, $order_id]);
}
function is_order_open($order_id) {
    $order = one("SELECT status FROM orders WHERE id=?", [$order_id]);
    return $order && $order['status'] === 'OPEN';
}


query("INSERT INTO settings (id) VALUES (?) ON DUPLICATE KEY UPDATE id=id", [$business_id]);
$r = $_GET['r'] ?? '';

switch ($r) {
  case 'categories':
    render('categories');
    break;

  case 'categories/create':
    $name = trim($_POST['name'] ?? '');
    if ($name) {
      // Avoid duplicate names within the same business
      $existing = one("SELECT id FROM categories WHERE business_id = ? AND name = ?", [$business_id, $name]);
      if (!$existing) {
        query("INSERT INTO categories(name, business_id) VALUES (?, ?)", [$name, $business_id]);
      }
    }
    redirect(BASE_URL . '/public/?r=categories');
    break;

  case 'categories/set_status':
    $id = (int)($_GET['id'] ?? 0);
    $status = (int)($_GET['status'] ?? 1); 
    query("UPDATE categories SET is_active=? WHERE id=? AND business_id = ?", [$status, $id, $business_id]);

    if ($status == 0) {
        query("UPDATE items SET is_active=0 WHERE category_id=? AND business_id = ?", [$id, $business_id]);
    }
    redirect(BASE_URL . '/public/?r=categories');
    break;

  case 'categories/delete':
    $id = (int)($_GET['id'] ?? 0);
    query("DELETE FROM categories WHERE id=? AND business_id = ?", [$id, $business_id]);
    redirect(BASE_URL . '/public/?r=categories');
    break;

  case 'items':
    render('items');
    break;
    // ---------------------------------------------------------
    // SECURITY: Get Business ID for all item operations
    // ---------------------------------------------------------
    $current_business = getCurrentBusiness();
    $business_id = $current_business['business_id'];

    // 1. DELETE ITEM (Secured)
    case 'items/delete':
        if (isset($_GET['id'])) {
            $id = $_GET['id'];

            // Security Check: Only fetch image if the item belongs to THIS business
            $row = row("SELECT img FROM new_items WHERE id = ? AND business_id = ?", [$id, $business_id]);
            
            if ($row) {
                // Delete image file if it exists
                if (!empty($row['img'])) {
                    $file = __DIR__ . "/uploads/" . $row['img'];
                    if (file_exists($file)) unlink($file);
                }

                // Execute Delete
                query("DELETE FROM new_items WHERE id = ? AND business_id = ?", [$id, $business_id]);
                
                echo "<script>alert('Item Deleted Successfully'); window.location='" . BASE_URL . "/public/?r=items';</script>";
            } else {
                echo "<script>alert('Access Denied: Item not found.'); window.location='" . BASE_URL . "/public/?r=items';</script>";
            }
        }
        break;

    // 2. SHOW EDIT PAGE (Secured)
    case 'items/edit':
        if (isset($_GET['id'])) {
            $id = $_GET['id'];
            
            // Security Check: Only fetch if business_id matches
            $item = row("SELECT * FROM new_items WHERE id = ? AND business_id = ?", [$id, $business_id]);
            
            if (!$item) { 
                die("Access Denied or Item Not Found"); 
            }
            
            require_once __DIR__ . "/../src/views/edit_item.php"; 
        }
        break;

    // 3. HANDLE UPDATE FORM SUBMISSION (Secured)
    case 'items/update':
        $id = $_POST['id'];
        $imgName = $_POST['old_img']; 

        // Handle New Image Upload
        if (!empty($_FILES["img"]["name"])) {
            $ext = pathinfo($_FILES["img"]["name"], PATHINFO_EXTENSION);
            $imgName = time() . "_" . uniqid() . "." . $ext;
            move_uploaded_file($_FILES["img"]["tmp_name"], __DIR__ . "/uploads/" . $imgName);
        }

        // Logic for Units
        $primary_unit = $_POST['primary_unit'];
        $alt_unit     = !empty($_POST['alternate_unit']) ? $_POST['alternate_unit'] : $primary_unit;
        $conv_factor  = !empty($_POST['conversion_factor']) ? $_POST['conversion_factor'] : 1;

        // SQL Update: Added `AND business_id = ?` to the WHERE clause
        $sql = "UPDATE new_items SET 
                item_name=?, short_name=?, hsn_code=?, tax_slab=?, company=?, item_group=?,
                primary_unit=?, alternate_unit=?, conversion_factor=?, price_per=?,
                purchase_price=?, sale_price=?, mrp=?,
                opening_qty_kg=?, img=?
                WHERE id=? AND business_id=?";  // <--- SECURITY LOCK

        query($sql, [
            $_POST['item_name'], $_POST['short_name'], $_POST['hsn_code'], $_POST['tax_slab'],
            $_POST['company'], $_POST['item_group'],
            $primary_unit, $alt_unit, $conv_factor, $_POST['price_per'],
            $_POST['purchase_price'], $_POST['sale_price'], $_POST['mrp'],
            $_POST['opening_qty_kg'], 
            $imgName,
            $id,
            $business_id // <--- Passed securely from session
        ]);

        echo "<script>alert('Item Updated Successfully'); window.location='" . BASE_URL . "/public/?r=items';</script>";
        break;
  case 'add_items':
    render('add_items');
    break;
  case 'items/save_item':
    $current_business = getCurrentBusiness(); 
    $business_id = $current_business['business_id'];

    $imgName = "";

    // 1. Handle Image Upload securely
    if (!empty($_FILES["img"]["name"])) {
        $ext = pathinfo($_FILES["img"]["name"], PATHINFO_EXTENSION);
        $imgName = time() . "_" . uniqid() . "." . $ext; 
        move_uploaded_file($_FILES["img"]["tmp_name"], __DIR__ . "/uploads/" . $imgName);
    }

    // 2. Logic for Units
    $primary_unit = $_POST['primary_unit'];
    $alt_unit     = !empty($_POST['alternate_unit']) ? $_POST['alternate_unit'] : $primary_unit;
    $conv_factor  = !empty($_POST['conversion_factor']) ? $_POST['conversion_factor'] : 1;

    // 3. Prepare SQL (Added business_id)
    $sql = "INSERT INTO new_items (
            business_id, item_name, short_name, hsn_code, tax_slab, company, item_group,
            primary_unit, alternate_unit, conversion_factor, price_per,
            purchase_price, sale_price, mrp,
            opening_qty_kg, opening_qty_gm, img
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    query($sql, [
        $business_id,           // <--- Added this
        $_POST['item_name'],
        $_POST['short_name'],
        $_POST['hsn_code'],
        $_POST['tax_slab'],
        $_POST['company'],
        $_POST['item_group'],
        $primary_unit,
        $alt_unit,
        $conv_factor,
        $_POST['price_per'],
        $_POST['purchase_price'],
        $_POST['sale_price'],
        $_POST['mrp'],
        $_POST['opening_qty_kg'],
        $_POST['opening_qty_gm'],
        $imgName
    ]);

    echo "<script>alert('Item Added Successfully'); window.location='" . BASE_URL . "/public/?r=items';</script>";
    break;
  case 'create_account':
    render('create_account');
    break;
  case 'create_accounts/create':
    $message = "";

  if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $business_id = $current_business['business_id'];
        $name            = $_POST['name'] ?? '';
        $print_as        = $_POST['print_as'] ?? $name;
        $group_name      = $_POST['group_name'] ?? '';
        $opening_balance = $_POST['opening_balance'] ?? 0;
        $drcr            = $_POST['drcr'] ?? 'Dr';

        $address1        = $_POST['address1'] ?? '';
        $address2        = $_POST['address2'] ?? '';
        $city            = $_POST['city'] ?? '';
        $pincode         = $_POST['pincode'] ?? '';
        $state           = $_POST['state'] ?? '';
        $mobile          = $_POST['mobile'] ?? '';
        $phone           = $_POST['phone'] ?? '';
        $email           = $_POST['email'] ?? '';
        $contact_person  = $_POST['contact_person'] ?? '';
        $pan             = $_POST['pan'] ?? '';

        // 2. Updated Query to include business_id
        query("
            INSERT INTO accounts 
            (business_id, name, print_as, group_name, opening_balance, drcr,
            address1, address2, city, pincode, state,
            mobile, phone, email, contact_person, pan)
            VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
        ", [
            $business_id, // <--- Added this
            $name, $print_as, $group_name, $opening_balance, $drcr,
            $address1, $address2, $city, $pincode, $state,
            $mobile, $phone, $email, $contact_person, $pan
        ]);

        $message = "Account Successfully Created!";
    }
    redirect(BASE_URL . '/public/?r=sale');
    break;
    case 'sale':
    render('sale');
    break;
  case 'orders':
    render('orders');
    break;
  case 'orders/new':
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $order_type = trim($_POST['order_type'] ?? 'table');
        $table_no_post = trim($_POST['table_no'] ?? '');
        $customer_name = trim($_POST['customer_name'] ?? '');
        $customer_mobile = trim($_POST['customer_mobile'] ?? '');

        if (strtolower($order_type) === 'takeaway') {
            $table_no = 'Takeaway';
        } else {
            $table_no = $table_no_post;
        }

        query("INSERT INTO customer (name, mobile_no, business_id) VALUES (?, ?, ?)", 
              [$customer_name, $customer_mobile, $business_id]);
        $customer_sno = db()->lastInsertId();

        // 🔹 get global gst setting
        $settings = one("SELECT gst_applicable FROM settings WHERE id=?", [$business_id]);
        $gst_enabled = (int)($settings['gst_applicable'] ?? 0);

        query("INSERT INTO orders (table_no, status, subtotal, discount, tax, total, payment_method, customer_sno, gst_enabled, business_id) 
               VALUES (?, 'OPEN', 0, 0, 0, 0, '', ?, ?, ?)", 
               [$table_no, $customer_sno, $gst_enabled, $business_id]);
        $id = db()->lastInsertId();

        redirect(BASE_URL . '/public/?r=orders/show&id=' . $id);
        exit;
    }
    render('order_new');
    break;

  case 'orders/show':
    render('order_show');
    break;

  case 'orders/add_item':
    $order_id = (int)$_POST['order_id'];
    if (!is_order_open($order_id)) {
        redirect(BASE_URL . '/public/?r=orders/show&id=' . $order_id);
        break;
    }
    $item = one("SELECT * FROM items WHERE id=? AND business_id = ?", [(int)$_POST['item_id'], $business_id]);
    $qty  = max(1, (int)$_POST['qty']);
    if ($item) {
      query("INSERT INTO order_items(order_id,item_id,item_name,price,qty,business_id) VALUES (?,?,?,?,?,?)",
        [$order_id,$item['id'],$item['name'],$item['price'],$qty,$business_id]);
      recalc_order_totals($order_id);
    }
    redirect(BASE_URL . '/public/?r=orders/show&id=' . $order_id);
    break;

  case 'orders/update_item':
    $oi_id = (int)$_POST['oi_id'];
    $order_id = (int)$_POST['order_id'];
    if (!is_order_open($order_id)) {
        redirect(BASE_URL . '/public/?r=orders/show&id=' . $order_id);
        break;
    }
    $qty = max(1, (int)$_POST['qty']);
    query("UPDATE order_items SET qty=? WHERE id=?", [$qty,$oi_id]);
    recalc_order_totals($order_id);
    redirect(BASE_URL . '/public/?r=orders/show&id=' . $order_id);
    break;

  case 'orders/remove_item':
    $oi_id = (int)$_GET['oi_id'];
    $order_id = (int)$_GET['order_id'];
    if (!is_order_open($order_id)) {
        redirect(BASE_URL . '/public/?r=orders/show&id=' . $order_id);
        break;
    }
    query("DELETE FROM order_items WHERE id=?", [$oi_id]);
    recalc_order_totals($order_id);
    redirect(BASE_URL . '/public/?r=orders/show&id=' . $order_id);
    break;

  case 'orders/discount':
    $order_id = (int)$_POST['order_id'];
    if (!is_order_open($order_id)) {
        redirect(BASE_URL . '/public/?r=orders/show&id=' . $order_id);
        break;
    }
    $discount = (float)($_POST['discount'] ?? 0);
    query("UPDATE orders SET discount=? WHERE id=? AND business_id = ?", [$discount, $order_id, $business_id]);
    recalc_order_totals($order_id);
    redirect(BASE_URL . '/public/?r=orders/show&id=' . $order_id);
    break;

  case 'orders/toggle_gst':
    $order_id = (int)$_POST['order_id'];
    if (!is_order_open($order_id)) {
        redirect(BASE_URL . '/public/?r=orders/show&id=' . $order_id);
        break;
    }
    $gst_enabled = isset($_POST['gst_enabled']) ? 1 : 0;
    query("UPDATE orders SET gst_enabled=? WHERE id=? AND business_id = ?", [$gst_enabled, $order_id, $business_id]);
    recalc_order_totals($order_id);
    redirect(BASE_URL . '/public/?r=orders/show&id=' . $order_id);
    break;

  case 'orders/pay':
    $order_id = $_POST['order_id'];
    $method   = $_POST['payment_method'] ?? 'CASH';
    recalc_order_totals($order_id);
    query("UPDATE orders SET status='PAID', payment_method=? WHERE id=? AND business_id = ?", [$method, $order_id, $business_id]);
    redirect(BASE_URL . '/public/?r=orders/show&id=' . $order_id);
    break;

  case 'orders/mark_due':
    $order_id = (int)$_POST['order_id'];

    // Get order details
    $order = one("SELECT * FROM orders WHERE id=? AND business_id=?", 
        [$order_id, $business_id]);

    if ($order) {

        // Get customer details
        $customer = one("SELECT * FROM customer WHERE sno=?", 
            [$order['customer_sno']]);

        $customer_name = $customer['name'] ?? 'Unknown';
        $customer_mobile = $customer['mobile_no'] ?? '';

        $total_bill = floatval($order['total']);
        $paid = 0;  // When marking as due, assume no payment made.
        $due = $total_bill;

        // Get previous outstanding
        $row = one("SELECT 
                        SUM(due) AS total_due,
                        SUM(outstanding) AS total_outstanding
                    FROM dues 
                    WHERE mobile = ? AND business_id = ?",
                    [$customer_mobile, $business_id]);

        $prev_outstanding = floatval($row['total_outstanding']);
        $outstanding = $prev_outstanding + $due;

        // Insert Due Entry
        // Insert Due Entry
      query("INSERT INTO dues 
        (order_id, customer_name, mobile, bill_amount, paid, due, outstanding, leisure, business_id)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
        [
            $order_id,           // <-- FIXED
            $customer_name,
            $customer_mobile,
            $total_bill,
            0,                   // paid
            $due,
            $outstanding,
            0,                   // leisure
            $business_id
        ]
      );


        // Mark Order as Due
        query("UPDATE orders SET status='DUE' WHERE id=? AND business_id=?",
              [$order_id, $business_id]);
    }

    redirect(BASE_URL . '/public/?r=orders/show&id=' . $order_id);
    break;


  case 'orders/cancel':
    $order_id = (int)$_GET['id'];
    query("UPDATE orders SET status='CANCELLED' WHERE id=? AND business_id = ?", [$order_id, $business_id]);
    redirect(BASE_URL . '/public/?r=orders/show&id=' . $order_id);
    break;

  case 'orders/receipt':
    require __DIR__ . '/../src/views/receipt.php';
    break;

  case 'reports':
    render('reports');
    break;

  case 'reports.csv':
    $from = $_GET['from'] ?? date('Y-m-01');
    $to   = $_GET['to']   ?? date('Y-m-d');

    $rows = all_rows("
        SELECT o.id, o.created_at, o.table_no, o.total,
               c.name AS customer_name, c.mobile_no AS customer_mobile
        FROM orders o
        LEFT JOIN customer c ON o.customer_sno = c.sno
        WHERE o.business_id = ? AND DATE(o.created_at) BETWEEN ? AND ?
          AND o.status='PAID'
        ORDER BY o.created_at DESC
    ", [$business_id,$from,$to]);

    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="reports.csv"');
    $out = fopen('php://output', 'w');

    // Add headers
    fputcsv($out, ['ID','Customer Name','Customer Mobile','Date','Table','Total']);

    foreach ($rows as $r) {
        fputcsv($out, [
            $r['id'],
            $r['customer_name'],
            $r['customer_mobile'],
            $r['created_at'],
            $r['table_no'],
            $r['total']
        ]);
    }

    fclose($out);
    exit;
    break;
  case 'due':
    render('due');
    break;

case 'due/new':
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {

        $customer_name = trim($_POST['customer_name']);
        $mobile        = trim($_POST['mobile']);
        $bill_amount   = floatval($_POST['bill_amount']);
        $paid          = floatval($_POST['paid'] ?? 0);

        // Due Calculation
        $due = max(0, $bill_amount - $paid);

        // Leisure (extra payment)
        $leisure = ($paid > $bill_amount) ? ($paid - $bill_amount) : 0;

        // Outstanding (previous dues)
        $row = one("SELECT SUM(due) AS total_outstanding 
                    FROM dues 
                    WHERE mobile = ? AND business_id=?", 
                    [$mobile, $business_id]);

        $outstanding = floatval($row['total_outstanding']) + $due;

        // Insert into dues table
        query("INSERT INTO dues (order_id, customer_name, mobile, bill_amount, paid, due, outstanding, leisure, business_id)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
               [$order_id, $customer_name, $mobile, $bill_amount, $paid, $due, $outstanding, $leisure, $business_id]);

        redirect(BASE_URL . "/public/?r=due");
        exit;
    }

    render('due_new');
    break;

case 'due/view':
    render('due_view');
    break;
case 'due/update':
    $id = intval($_GET['id']);
    $amount = floatval($_GET['amount']);

    // Fetch existing record
    $d = one("SELECT * FROM dues WHERE id=? AND business_id=?", [$id, $business_id]);

    if (!$d) {
        die("Due not found");
    }

    $new_paid = $d['paid'] + $amount;
    $new_due = $d['bill_amount'] - $new_paid;

    if ($new_due < 0) $new_due = 0;

    // outstanding = still pending
    $outstanding = $new_due;

    // leisure = extra given (paid more than bill)
    $leisure = ($new_paid > $d['bill_amount']) ? ($new_paid - $d['bill_amount']) : 0;

    // update dues record
    query("
        UPDATE dues 
        SET paid=?, due=?, outstanding=?, leisure=?, updated_at=NOW() 
        WHERE id=? AND business_id=?
    ", [$new_paid, $new_due, $outstanding, $leisure, $id, $business_id]);

    if ($new_due == 0) {
        query("
            UPDATE orders
            SET status='PAID',
                payment_method='DUE_SETTLEMENT',
                updated_at = NOW()
            WHERE id=? AND business_id=?
        ", [$d['order_id'], $business_id]);
    }

    redirect("?r=due");
    break;


case 'due/fullpaid':
    $id = intval($_GET['id']);

    // fetch due record
    $d = one("SELECT * FROM dues WHERE id=? AND business_id=?", [$id, $business_id]);
    if (!$d) die("Due not found");

    // fully update dues entry
    query("
        UPDATE dues
        SET paid = bill_amount,
            due = 0,
            outstanding = 0,
            leisure = 0,
            updated_at = NOW()
        WHERE id=? AND business_id=?
    ", [$id, $business_id]);

    // if this due is linked to an order, update the order also
    if (!empty($d['order_id'])) {
        query("
            UPDATE orders
            SET status='PAID',
                payment_method='DUE_SETTLEMENT'
            WHERE id=? AND business_id=?
        ", [$d['order_id'], $business_id]);
    }

    redirect("?r=due");
    break;

  case 'settings':
    render('settings');
    break;

  case 'settings/save':
    $business_name = trim($_POST['business_name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $gstin = trim($_POST['gstin'] ?? '');
    $gst_rate = (float)($_POST['gst_rate'] ?? 0);
    $gst_applicable = (int)($_POST['gst_applicable'] ?? 0);

    query("UPDATE settings 
              SET business_name=?, phone=?, address=?, gstin=?, gst_rate=?, gst_applicable=? 
            WHERE id=?",
          [$business_name,$phone,$address,$gstin,$gst_rate,$gst_applicable,$business_id]);

    redirect(BASE_URL . '/public/?r=settings');
    break;

  case 'api/items':
    $q = trim($_GET['q'] ?? '');
    $items = all_rows("SELECT id,name,price FROM items WHERE business_id = ? AND is_active=1 AND name LIKE ? ORDER BY name LIMIT 10", [$business_id, "%$q%"]);
    header('Content-Type: application/json');
    echo json_encode($items);
    exit;
    break;

  default:
    render('dashboard');
}
