<?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;

    // --- [NEW] 2.5 Logic for Dynamic Fields (JSON) ---
    $final_attributes = [];
    if (isset($_POST['custom_keys']) && isset($_POST['custom_values'])) {
        $keys = $_POST['custom_keys'];
        $values = $_POST['custom_values'];

        for ($i = 0; $i < count($keys); $i++) {
            $key = trim($keys[$i]);
            $val = trim($values[$i]);
            
            // Format Key: "color" -> "Color"
            $key = ucwords(strtolower($key));

            if (!empty($key) && !empty($val)) {
                $final_attributes[$key] = $val;
            }
        }
    }
    // Convert array to JSON string, or NULL if empty
    $json_data = !empty($final_attributes) ? json_encode($final_attributes) : null;
    // --------------------------------------------------


    // 3. Prepare SQL (Added dynamic_data column)
    $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, dynamic_data
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    query($sql, [
        $business_id,
        $_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'] ?? 0, // Ensure this key exists or default to 0
        $imgName,
        $json_data // <--- Added this (The JSON String)
    ]);

    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':
    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 'purchase':
    render('purchase');
    break;

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

  case 'reports/stock':
    render('report_stock');
    break;

  case 'reports/cash_credit':
    render('report_cash_credit');
    break;

  case 'reports/party_balance':
    render('report_party_balance');
    break;

  case 'reports/ledger':
    render('report_ledger');
    break;

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

  case 'latest_sale_id':
    header('Content-Type: application/json');
    $latest_sale = one("SELECT id FROM sales WHERE business_id = ? ORDER BY id DESC LIMIT 1", [$business_id]);
    if ($latest_sale) {
        echo json_encode(['success' => true, 'sale_id' => $latest_sale['id']]);
    } else {
        echo json_encode(['success' => false]);
    }
    exit;
    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 'invoice':
    render('invoice');
    break;
  case 'settings':
    render('settings');
    break;
  case 'settings/save_invoice_type':
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $current_business = getCurrentBusiness();
        $business_id = $current_business['business_id'];

        $name = $_POST['type_name'];
        $tax_type = $_POST['tax_type']; // inclusive or exclusive
        $prefix = $_POST['prefix'];
        $start = $_POST['start_number'];

        // Insert new Invoice Type
        query("INSERT INTO invoice_types (business_id, type_name, tax_type, prefix, start_number) VALUES (?,?,?,?,?)", 
            [$business_id, $name, $tax_type, $prefix, $start]);

        header('Location: ' . BASE_URL . '/public/?r=settings'); // Redirect back to settings
        exit;
    }
  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');
}
