<?php
session_start();

// Handle AJAX requests first to prevent any HTML output
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Turn off error reporting for AJAX to prevent HTML output
    ini_set('display_errors', 0);
    error_reporting(0);
    
    // Debug: Log that AJAX request was received
    error_log("=== AJAX REQUEST START ===");
    error_log("POST data: " . print_r($_POST, true));
    error_log("FILES data: " . print_r($_FILES, true));
    error_log("REQUEST_URI: " . $_SERVER['REQUEST_URI']);
    error_log("SCRIPT_NAME: " . $_SERVER['SCRIPT_NAME']);
    
    
    // Test if any POST request is reaching this point
    error_log("=== ANY POST REQUEST RECEIVED ===");
    error_log("POST data: " . print_r($_POST, true));
    error_log("FILES data: " . print_r($_FILES, true));
    error_log("REQUEST_METHOD: " . $_SERVER['REQUEST_METHOD']);
    error_log("CONTENT_TYPE: " . ($_SERVER['CONTENT_TYPE'] ?? 'not set'));
    
    
    if (!isset($_SESSION['user_id'])) {
        header('Content-Type: application/json');
        echo json_encode(['status' => 'error', 'message' => 'Session expired. Please login again.']);
        exit();
    }
    
    require_once __DIR__ . '/../inc/db.php'; // $conn
    
    // Handle AJAX requests
    header('Content-Type: application/json');
    
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add_purchase':
                $supplier_name = trim($_POST['supplier_name'] ?? '');
                $supplier_contact = trim($_POST['supplier_contact'] ?? '');
                $supplier_address = trim($_POST['supplier_address'] ?? '');
                $product_name = trim($_POST['product_name'] ?? '');
                $hsn_code = trim($_POST['hsn_code'] ?? '');
                $purchase_price = floatval($_POST['purchase_price'] ?? 0);
                $quantity = intval($_POST['quantity'] ?? 0);
                $total_amount = floatval($_POST['total_amount'] ?? 0);
                $bill_number = trim($_POST['bill_number'] ?? '');
                $bill_date = $_POST['bill_date'] ?? '';
                $payment_status = $_POST['payment_status'] ?? 'pending';
                
                // Debug: Log payment status
                error_log("Add Purchase - Payment status received: " . $payment_status);
                
                $amount_paid = floatval($_POST['amount_paid'] ?? 0);
                
                // Add product directly to purchase_items (no separate products table)
                $sell_price = floatval($_POST['sell_price'] ?? $purchase_price);
                $distributor = trim($_POST['distributor'] ?? '');
                $product_category = trim($_POST['product_category'] ?? '');
                $details = trim($_POST['details'] ?? '');
                
                if (empty($supplier_name) || empty($product_name) || $quantity <= 0 || $purchase_price <= 0 || $sell_price <= 0) {
                    echo json_encode(['status' => 'error', 'message' => 'Please fill all required fields']);
                    exit;
                }
                
                // Handle images upload (simplified)
                $uploadDir = __DIR__ . '/uploads/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0777, true);
                }
                
                $imageNames = [];
                
                // Image upload handling (using working code from ecommerce-add-new-products.php)
                $imageNames = [];
                if (!empty($_FILES['images']['name'][0])) {
                    foreach ($_FILES['images']['tmp_name'] as $i => $tmp) {
                        if ($_FILES['images']['error'][$i] === UPLOAD_ERR_OK) {
                            $ext  = pathinfo($_FILES['images']['name'][$i], PATHINFO_EXTENSION);
                            $file = uniqid('img_', true) . '.' . $ext;
                            move_uploaded_file($tmp, $uploadDir . $file);
                            $imageNames[] = $file;
                        }
                    }
                }
                
                $images_json = json_encode($imageNames);

                // Insert directly into purchase_items with all product info
                $sql = "INSERT INTO purchase_items (supplier_name, supplier_contact, supplier_address, product_name, hsn_code, purchase_price, sell_price, distributor, product_category, details, quantity, total_amount, bill_number, bill_date, payment_status, amount_paid, images) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                $stmt = $conn->prepare($sql);
                $stmt->bind_param("sssssdsssssdsssss", $supplier_name, $supplier_contact, $supplier_address, $product_name, $hsn_code, $purchase_price, $sell_price, $distributor, $product_category, $details, $quantity, $total_amount, $bill_number, $bill_date, $payment_status, $amount_paid, $images_json);
                
                if ($stmt->execute()) {
                    echo json_encode(['status' => 'success', 'message' => 'Product added successfully and purchase recorded']);
                } else {
                    echo json_encode(['status' => 'error', 'message' => 'Failed to add purchase: ' . $stmt->error]);
                }
                $stmt->close();
                exit;
                
            case 'update_purchase':
                $id = intval($_POST['id'] ?? 0);
                if ($id <= 0) {
                    echo json_encode(['status' => 'error', 'message' => 'Invalid purchase ID']);
                    exit;
                }
                
                $supplier_name = trim($_POST['supplier_name'] ?? '');
                $supplier_contact = trim($_POST['supplier_contact'] ?? '');
                $supplier_address = trim($_POST['supplier_address'] ?? '');
                $product_name = trim($_POST['product_name'] ?? '');
                $hsn_code = trim($_POST['hsn_code'] ?? '');
                $purchase_price = floatval($_POST['purchase_price'] ?? 0);
                $quantity = intval($_POST['quantity'] ?? 0);
                $total_amount = floatval($_POST['total_amount'] ?? 0);
                $bill_number = trim($_POST['bill_number'] ?? '');
                $bill_date = $_POST['bill_date'] ?? '';
                $payment_status = $_POST['payment_status'] ?? 'pending';
                $amount_paid = floatval($_POST['amount_paid'] ?? 0);
                
                $sell_price = floatval($_POST['sell_price'] ?? $purchase_price);
                $distributor = trim($_POST['distributor'] ?? '');
                $product_category = trim($_POST['product_category'] ?? '');
                $details = trim($_POST['details'] ?? '');
                
                if (empty($supplier_name) || empty($product_name) || $quantity <= 0 || $purchase_price <= 0 || $sell_price <= 0) {
                    echo json_encode(['status' => 'error', 'message' => 'Please fill all required fields']);
                    exit;
                }
                
                // Handle images upload (simplified)
                $uploadDir = __DIR__ . '/uploads/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0777, true);
                }
                
                $imageNames = [];
                
                // Image upload handling for update (using working code from ecommerce-add-new-products.php)
                $imageNames = [];
                if (!empty($_FILES['images']['name'][0])) {
                    foreach ($_FILES['images']['tmp_name'] as $i => $tmp) {
                        if ($_FILES['images']['error'][$i] === UPLOAD_ERR_OK) {
                            $ext  = pathinfo($_FILES['images']['name'][$i], PATHINFO_EXTENSION);
                            $file = uniqid('img_', true) . '.' . $ext;
                            move_uploaded_file($tmp, $uploadDir . $file);
                            $imageNames[] = $file;
                        }
                    }
                    $images_json = json_encode($imageNames);
                } else {
                    // Keep existing images if no new ones uploaded
                    $existing_sql = "SELECT images FROM purchase_items WHERE id = ?";
                    $existing_stmt = $conn->prepare($existing_sql);
                    $existing_stmt->bind_param("i", $id);
                    $existing_stmt->execute();
                    $existing_result = $existing_stmt->get_result();
                    $existing_row = $existing_result->fetch_assoc();
                    $images_json = $existing_row['images'] ?? '[]';
                    $existing_stmt->close();
                }
                
                $sql = "UPDATE purchase_items SET supplier_name=?, supplier_contact=?, supplier_address=?, product_name=?, hsn_code=?, purchase_price=?, sell_price=?, distributor=?, product_category=?, details=?, quantity=?, total_amount=?, bill_number=?, bill_date=?, payment_status=?, amount_paid=?, images=? WHERE id=?";
                $stmt = $conn->prepare($sql);
                $stmt->bind_param("sssssdsssssdsssssi", $supplier_name, $supplier_contact, $supplier_address, $product_name, $hsn_code, $purchase_price, $sell_price, $distributor, $product_category, $details, $quantity, $total_amount, $bill_number, $bill_date, $payment_status, $amount_paid, $images_json, $id);
                
                if ($stmt->execute()) {
                    echo json_encode(['status' => 'success', 'message' => 'Purchase updated successfully']);
                } else {
                    echo json_encode(['status' => 'error', 'message' => 'Failed to update purchase: ' . $stmt->error]);
                }
                $stmt->close();
                exit;
                
            case 'delete_purchase':
                $id = intval($_POST['id'] ?? 0);
                if ($id <= 0) {
                    echo json_encode(['status' => 'error', 'message' => 'Invalid purchase ID']);
                    exit;
                }
                
                $sql = "DELETE FROM purchase_items WHERE id = ?";
                $stmt = $conn->prepare($sql);
                $stmt->bind_param("i", $id);
                
                if ($stmt->execute()) {
                    echo json_encode(['status' => 'success', 'message' => 'Purchase deleted successfully']);
                } else {
                    echo json_encode(['status' => 'error', 'message' => 'Failed to delete purchase: ' . $stmt->error]);
                }
                $stmt->close();
                exit;
        }
    }
    exit;
}

// Regular page load (non-AJAX)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (!isset($_SESSION['user_id'])) {
    header("Location: auth-basic-signin.php");
    exit();
}

require_once __DIR__ . '/../inc/db.php';

$user_id = $_SESSION['user_id'];

// Fetch user data
$sql = "SELECT name, email, phone, mobile, address, instagram, facebook, profile_image 
        FROM users WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
$stmt->close();


// Get all purchases
$purchases = [];
$sql = "SELECT * FROM purchase_items ORDER BY created_at DESC";
$result = $conn->query($sql);
if ($result) {
    while ($row = $result->fetch_assoc()) {
        // Parse images JSON
        $row['images'] = json_decode($row['images'], true) ?: [];
        $purchases[] = $row;
    }
}

// No need for products table - everything is in purchase_items now
?>

<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!--favicon-->
    <link rel="icon" href="assets/images/logo-icon.png" type="image/png" />
    <!--plugins-->
    <link href="assets/plugins/simplebar/css/simplebar.css" rel="stylesheet" />
    <link href="assets/plugins/perfect-scrollbar/css/perfect-scrollbar.css" rel="stylesheet" />
    <link href="assets/plugins/metismenu/css/metisMenu.min.css" rel="stylesheet" />
    <link href="assets/plugins/datatable/css/dataTables.bootstrap5.min.css" rel="stylesheet" />
    <!-- loader-->
    <link href="assets/css/pace.min.css" rel="stylesheet" />
    <script src="assets/js/pace.min.js"></script>
    <!-- Bootstrap CSS -->
    <link href="assets/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/css/bootstrap-extended.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap" rel="stylesheet">
    <link href="assets/css/app.css" rel="stylesheet">
    <link href="assets/css/icons.css" rel="stylesheet">
    <link href="assets/plugins/Drag-And-Drop/dist/imageuploadify.min.css" rel="stylesheet" />
    
    <title>Product Management - Kumawat Computer</title>
</head>

<body class="bg-theme bg-theme2">
    <!--wrapper-->
    <div class="wrapper">
        <!--sidebar wrapper -->
        <div class="sidebar-wrapper" data-simplebar="true">
            <div class="sidebar-header">
                <div>
                    <img src="assets/images/logo-icon.png" class="logo-icon" alt="logo icon">
                </div>
                <div>
                    <h4 class="logo-text">Kumawat</h4>
                </div>
                <div class="toggle-icon ms-auto"><i class='bx bx-arrow-back'></i>
                </div>
             </div>
            <!--navigation-->
            <ul class="metismenu" id="menu">
                <li>
                    <a href="index.php">
                        <div class="parent-icon"><i class='bx bx-home-alt'></i>
                        </div>
                        <div class="menu-title">Home</div>
                    </a> 
                </li>  
                <li>
                    <a href="table-datatable.php">
                        <div class="parent-icon"><i class="bx bx-grid-alt"></i>
                        </div>
                        <div class="menu-title">Product Tables</div>
                    </a> 
                </li>
              
                <li>
                    <a href="ecommerce-products.php">
                        <div class="parent-icon"><i class='bx bx-briefcase-alt'></i>
                        </div>
                        <div class="menu-title">Products</div>
                    </a> 
                </li>  
                <li>
                    <a href="ecommerce-add-new-products.php">
                        <div class="parent-icon"><i class='bx bx-store'></i>
                        </div>
                        <div class="menu-title">Add New Products</div>
                    </a> 
                </li> 
                <li>
                    <a href="temprary.php">
                        <div class="parent-icon"><i class='bx bx-repeat'></i>
                        </div>
                        <div class="menu-title">Temporary</div>
                    </a> 
                </li> 
                <li>
                    <a href="permanent-customer.php">
                        <div class="parent-icon"><i class='bx bx-bookmark-heart'></i>
                        </div>
                        <div class="menu-title">Permanent Customer</div>
                    </a> 
                </li>
                <li>
                    <a href="party-customer.php">
                        <div class="parent-icon"><i class='bx bx-cookie'></i>
                        </div>
                        <div class="menu-title">Party</div>
                    </a> 
                </li>
                <li>
                    <a href="sell-purchase-selection.php">
                        <div class="parent-icon"><i class='bx bx-transfer'></i>
                        </div>
                        <div class="menu-title">Sell & Purchase</div>
                    </a> 
                </li>
                <li>
                    <a href="sell-purchase-reports.php">
                        <div class="parent-icon"><i class='bx bx-bar-chart-alt-2'></i>
                        </div>
                        <div class="menu-title">Sell & Purchase Reports</div>
                    </a> 
                </li>
                <li>
                    <a href="purchase-management.php" class="mm-active">
                        <div class="parent-icon"><i class='bx bx-plus-circle'></i>
                        </div>
                        <div class="menu-title">Add Products</div>
                    </a> 
                </li>
                <li>
                    <a href="ecommerce-orders.php">
                        <div class="parent-icon"><i class='bx bx-cart'></i>
                        </div>
                        <div class="menu-title">History</div>
                    </a> 
                </li> 
                <li>
                    <a href="user-profile.php">
                        <div class="parent-icon"><i class="bx bx-user-circle"></i>
                        </div>
                        <div class="menu-title">User Profile</div>
                    </a>
                </li>  
            </ul>
            <!--end navigation-->
        </div>
        <!--end sidebar wrapper -->
        <!--start header -->
        <header>
            <div class="topbar d-flex align-items-center">
                <nav class="navbar navbar-expand gap-3">
                    <div class="mobile-toggle-menu"><i class='bx bx-menu'></i>
                    </div>
                    <div class="search-bar flex-grow-1">
                        <div class="position-relative search-bar-box">
                            <input type="text" class="form-control search-control" placeholder="Type to search..."> <span class="position-absolute top-50 search-show translate-middle-y"><i class='bx bx-search'></i></span>
                            <span class="position-absolute top-50 search-close translate-middle-y"><i class='bx bx-x'></i></span>
                        </div>
                    </div>
                    <div class="top-menu ms-auto">
                        <ul class="navbar-nav align-items-center gap-1">
                            <li class="nav-item mobile-search-icon d-flex d-lg-none" data-bs-toggle="modal" data-bs-target="#SearchModal">
                                <a class="nav-link" href="avascript:;"><i class='bx bx-search'></i>
                                </a>
                            </li>  
                        </ul>
                    </div>
                    <div class="user-box dropdown px-3">
                        <a class="d-flex align-items-center nav-link dropdown-toggle gap-3 dropdown-toggle-nocaret" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <img src="<?= htmlspecialchars($user['profile_image'] ?: 'assets/images/avatars/avatar-2.png') ?>"
                                             alt="Profile" class="user-img">
                            <div class="user-info">
                                <p class="user-name mb-0"><?= htmlspecialchars($user['name']) ?></p>
                                <p class="designattion mb-0"><?= htmlspecialchars($user['email']) ?></p>
                            </div>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item d-flex align-items-center" href="user-profile.php"><i class="bx bx-user fs-5"></i><span>Profile</span></a>
                            </li> 
                            <li>
                                <div class="dropdown-divider mb-0"></div>
                            </li>
                            <li><a class="dropdown-item d-flex align-items-center" href="logout.php"><i class="bx bx-log-out-circle"></i><span>Logout</span></a>
                            </li>
                        </ul>
                    </div>
                </nav>
            </div>
        </header>
        <!--end header -->
        <!--start page wrapper -->
        <div class="page-wrapper">
            <div class="page-content">
                <!-- Add Product/Purchase Form -->
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">Add New Product (Purchase)</h5>
                                <p class="text-muted mb-0">Adding a product means purchasing it from supplier</p>
                            </div>
                            <div class="card-body">
                                <form id="purchaseForm" enctype="multipart/form-data">
                                    <div class="row g-3">
                                        <div class="col-md-6">
                                            <label class="form-label">Supplier Name *</label>
                                            <input type="text" class="form-control" name="supplier_name" required>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">Supplier Contact</label>
                                            <input type="text" class="form-control" name="supplier_contact">
                                        </div>
                                        <div class="col-md-12">
                                            <label class="form-label">Supplier Address</label>
                                            <textarea class="form-control" name="supplier_address" rows="2"></textarea>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">Product Name *</label>
                                            <input type="text" class="form-control" name="product_name" id="productName" required placeholder="Enter product name">
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">Product Category</label>
                                            <input type="text" class="form-control" name="product_category" placeholder="e.g., Electronics, Computer Parts">
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">Sell Price (for inventory) *</label>
                                            <input type="number" class="form-control" name="sell_price" id="sellPrice" step="0.01" required placeholder="Enter selling price">
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">Distributor</label>
                                            <input type="text" class="form-control" name="distributor" id="distributor" placeholder="Enter distributor name">
                                        </div>
                                        <div class="col-md-12">
                                            <label class="form-label">Product Details</label>
                                            <textarea class="form-control" name="details" id="details" rows="3" placeholder="Enter product description, specifications, or any additional details"></textarea>
                                        </div>

                                        <div class="col-md-12">
                                            <div class="border border-3 p-4 rounded">
                                                <div class="mb-3">
                                                    <label for="formFileMultiple" class="form-label">Product Images</label>
                                                    <input id="image-uploadify" type="file" id="formFileMultiple" name="images[]" accept=".png,.jpg,.jpeg,image/*" multiple>
                                                    <small class="text-muted">Select one or more images (PNG, JPG, JPEG only)</small>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-4">
                                            <label class="form-label">HSN Code</label>
                                            <input type="text" class="form-control" name="hsn_code">
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">Purchase Price *</label>
                                            <input type="number" class="form-control" name="purchase_price" id="purchasePrice" step="0.01" required>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">Quantity *</label>
                                            <input type="number" class="form-control" name="quantity" id="quantity" required>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">Total Amount</label>
                                            <input type="number" class="form-control" name="total_amount" id="totalAmount" step="0.01" readonly>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">Bill Number</label>
                                            <input type="text" class="form-control" name="bill_number">
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">Bill Date *</label>
                                            <input type="date" class="form-control" name="bill_date" value="<?= date('Y-m-d') ?>" required>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">Payment Status</label>
                                            <select class="form-select" name="payment_status" id="paymentStatus" onchange="updatePaymentFields()">
                                                <option value="pending" selected>Pending</option>
                                                <option value="paid">Paid</option>
                                            </select>
                                        </div>
                                        <div class="col-md-6" id="amountPaidContainer">
                                            <label class="form-label">Amount Paid</label>
                                            <input type="number" class="form-control" name="amount_paid" id="amountPaid" step="0.01" value="0">
                                        </div>
                                        <div class="col-12">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="bx bx-plus"></i> Add Product (Purchase)
                                            </button>
                                            <button type="button" class="btn btn-secondary" onclick="resetForm()">Reset</button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Purchase History -->
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">Purchase History</h5>
                                <p class="text-muted mb-0">All product purchases and their details</p>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped" id="purchaseTable">
                                        <thead>
                                            <tr>
                                                <th>ID</th>
                                                <th>Supplier</th>
                                                <th>Product</th>
                                                <th>Quantity</th>
                                                <th>Price</th>
                                                <th>Total</th>
                                                <th>Paid</th>
                                                <th>Pending</th>
                                                <th>Bill Date</th>
                                                <th>Payment Status</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($purchases as $purchase): 
                                                // Calculate paid and pending amounts based on payment status
                                                if ($purchase['payment_status'] == 'paid') {
                                                    $paid_amount = $purchase['total_amount'];
                                                    $pending_amount = 0;
                                                } else {
                                                    $paid_amount = $purchase['amount_paid'];
                                                    $pending_amount = $purchase['total_amount'] - $purchase['amount_paid'];
                                                }
                                            ?>
                                            <tr>
                                                <td><?= $purchase['id'] ?></td>
                                                <td>
                                                    <strong><?= htmlspecialchars($purchase['supplier_name']) ?></strong><br>
                                                    <small class="text-muted"><?= htmlspecialchars($purchase['supplier_contact']) ?></small>
                                                </td>
                                                <td><?= htmlspecialchars($purchase['product_name']) ?></td>
                                                <td><?= $purchase['quantity'] ?></td>
                                                <td>₹<?= number_format($purchase['purchase_price'], 2) ?></td>
                                                <td>₹<?= number_format($purchase['total_amount'], 2) ?></td>
                                                <td class="text-success">₹<?= number_format($paid_amount, 2) ?></td>
                                                <td class="text-danger">₹<?= number_format($pending_amount, 2) ?></td>
                                                <td><?= date('d M Y', strtotime($purchase['bill_date'])) ?></td>
                                                <td>
                                                    <span class="badge bg-<?= $purchase['payment_status'] == 'paid' ? 'success' : 'danger' ?>">
                                                        <?= ucfirst($purchase['payment_status']) ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <button class="btn btn-sm btn-info" onclick="viewPurchase(<?= htmlspecialchars(json_encode($purchase)) ?>)" title="View Details">
                                                        <i class="bx bx-show"></i>
                                                    </button>
                                                    <button class="btn btn-sm btn-primary" onclick="editPurchase(<?= htmlspecialchars(json_encode($purchase)) ?>)" title="Edit">
                                                        <i class="bx bx-edit"></i>
                                                    </button>
                                                    <button class="btn btn-sm btn-danger" onclick="deletePurchase(<?= $purchase['id'] ?>)" title="Delete">
                                                        <i class="bx bx-trash"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!--end page wrapper -->

        <!-- View Purchase Modal -->
        <div class="modal fade" id="viewPurchaseModal" tabindex="-1" aria-labelledby="viewPurchaseModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="viewPurchaseModalLabel">Purchase Details</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body" id="purchaseDetails">
                        <!-- Purchase details will be loaded here -->
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-primary" onclick="printPurchase()">
                            <i class="bx bx-printer"></i> Print
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <!--start overlay-->
        <div class="overlay toggle-icon"></div>
        <!--end overlay-->
        <!--Start Back To Top Button--> <a href="javaScript:;" class="back-to-top"><i class='bx bxs-up-arrow-alt'></i></a>
        <!--End Back To Top Button-->
        <footer class="page-footer">
            <p class="mb-0">Copyright © 2021. All right reserved.</p>
        </footer>
    </div>
    <!--end wrapper-->
    <!--start switcher-->
    <div class="switcher-wrapper">
        <div class="switcher-btn"> <i class='bx bx-cog bx-spin'></i>
        </div>
        <div class="switcher-body">
            <div class="d-flex align-items-center">
                <h5 class="mb-0 text-uppercase">Theme Customizer</h5>
                <button type="button" class="btn-close ms-auto close-switcher" aria-label="Close"></button>
            </div>
            <hr/>
            <p class="mb-0">Gaussian Texture</p>
            <hr>
            <ul class="switcher">
                <li id="theme1"></li>
                <li id="theme2"></li>
                <li id="theme3"></li>
                <li id="theme4"></li>
                <li id="theme5"></li>
                <li id="theme6"></li>
            </ul>
            <hr>
            <p class="mb-0">Gradient Background</p>
            <hr>
            <ul class="switcher">
                <li id="theme7"></li>
                <li id="theme8"></li>
                <li id="theme9"></li>
                <li id="theme10"></li>
                <li id="theme11"></li>
                <li id="theme12"></li>
                <li id="theme13"></li>
                <li id="theme14"></li>
                <li id="theme15"></li>
              </ul>
        </div>
    </div>
    <!--end switcher-->
    <!-- Bootstrap JS -->
    <script src="assets/js/bootstrap.bundle.min.js"></script>
    <!--plugins-->
    <script src="assets/js/jquery.min.js"></script>
    <script src="assets/plugins/simplebar/js/simplebar.min.js"></script>
    <script src="assets/plugins/metismenu/js/metisMenu.min.js"></script>
    <script src="assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
    <script src="assets/plugins/apexcharts-bundle/js/apexcharts.min.js"></script>
    <script src="assets/plugins/datatable/js/jquery.dataTables.min.js"></script>
    <script src="assets/plugins/datatable/js/dataTables.bootstrap5.min.js"></script>
    <script src="assets/js/index.js"></script>
    <script src="assets/plugins/Drag-And-Drop/dist/imageuploadify.min.js"></script>
    <!--app JS-->
    <script src="assets/js/app.js"></script>

    <script>
        // Calculate total amount
        function calculateTotal() {
            const price = parseFloat(document.getElementById('purchasePrice').value) || 0;
            const quantity = parseInt(document.getElementById('quantity').value) || 0;
            const total = price * quantity;
            document.getElementById('totalAmount').value = total.toFixed(2);
            
            // Update payment fields if payment status is 'paid'
            updatePaymentOnTotalChange();
        }

        // Auto-calculate sell price based on purchase price (with markup)
        document.getElementById('purchasePrice').addEventListener('input', function() {
            const purchasePrice = parseFloat(this.value) || 0;
            const sellPriceField = document.getElementById('sellPrice');
            
            // Auto-suggest sell price (20% markup by default)
            if (sellPriceField.value === '' || sellPriceField.value === '0') {
                sellPriceField.value = (purchasePrice * 1.2).toFixed(2);
            }
            calculateTotal();
        });

        // Calculate total when price or quantity changes
        document.getElementById('quantity').addEventListener('input', calculateTotal);

        // Update payment fields based on payment status
        function updatePaymentFields() {
            const paymentStatus = document.getElementById('paymentStatus').value;
            const amountPaidInput = document.getElementById('amountPaid');
            const amountPaidContainer = document.getElementById('amountPaidContainer');
            const totalAmount = parseFloat(document.getElementById('totalAmount').value) || 0;
            
            // Always ensure the field is visible
            amountPaidContainer.style.display = 'block';
            
            switch(paymentStatus) {
                case 'pending':
                    // For pending, allow manual entry but default to 0
                    amountPaidInput.disabled = false;
                    amountPaidInput.style.backgroundColor = ''; // Normal white background
                    amountPaidInput.placeholder = 'Enter amount paid (if any)';
                    // Only set to 0 if it's currently empty or was auto-filled
                    if (amountPaidInput.value == totalAmount || amountPaidInput.value == '') {
                        amountPaidInput.value = 0;
                    }
                    break;
                    
                case 'paid':
                    amountPaidInput.value = totalAmount;
                    amountPaidInput.disabled = true;
                    amountPaidInput.style.backgroundColor = '#d4edda';
                    amountPaidInput.placeholder = 'Fully paid';
                    break;
            }
        }

        // Update payment fields when total amount changes
        function updatePaymentOnTotalChange() {
            const paymentStatus = document.getElementById('paymentStatus').value;
            const totalAmount = parseFloat(document.getElementById('totalAmount').value) || 0;
            const amountPaidInput = document.getElementById('amountPaid');
            
            if (paymentStatus === 'paid') {
                amountPaidInput.value = totalAmount;
            }
        }

        // Reset form function
        function resetForm() {
            document.getElementById('purchaseForm').reset();
            document.getElementById('paymentStatus').value = 'pending';
            document.getElementById('amountPaid').value = 0;
            document.getElementById('totalAmount').value = '';
            updatePaymentFields();
            
            // Clear image preview
            selectedImages = [];
            document.getElementById('imagePreview').style.display = 'none';
            document.getElementById('imageList').innerHTML = '';
            
            // Remove any hidden purchase_id field if editing
            const hiddenField = document.querySelector('input[name="purchase_id"]');
            if (hiddenField) {
                hiddenField.remove();
            }
            
            // Reset submit button text
            document.querySelector('button[type="submit"]').innerHTML = '<i class="bx bx-plus"></i> Add Product (Purchase)';
        }


        // Handle form submission
        document.getElementById('purchaseForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            // Check if uploadify is interfering
            console.log('Form element:', this);
            console.log('Form action:', this.action);
            console.log('Form method:', this.method);
            
            const formData = new FormData(this);
            const isUpdate = document.querySelector('input[name="purchase_id"]');
            
            if (isUpdate) {
                formData.append('action', 'update_purchase');
            } else {
                formData.append('action', 'add_purchase');
            }
            
            // Debug: Log form data
            console.log('Form data being sent:');
            for (let [key, value] of formData.entries()) {
                console.log(key, value);
            }
            
            // Debug: Check if files are in FormData
            const fileInput = document.getElementById('image-uploadify');
            console.log('File input files:', fileInput ? fileInput.files : 'File input not found');
            if (fileInput && fileInput.files) {
                console.log('Number of files:', fileInput.files.length);
                for (let i = 0; i < fileInput.files.length; i++) {
                    console.log('File ' + i + ':', fileInput.files[i].name, fileInput.files[i].size);
                }
            }
            
            // Debug: Check if images are in FormData
            console.log('Checking for images in FormData:');
            for (let [key, value] of formData.entries()) {
                if (key.includes('images')) {
                    console.log('Found images field:', key, value);
                }
            }
            
            console.log('Sending AJAX request to purchase-management.php');
            console.log('FormData entries:');
            for (let [key, value] of formData.entries()) {
                console.log(key, value);
            }
            
            fetch('purchase-management.php', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                console.log('Response received:', response);
                console.log('Response status:', response.status);
                
                if (!response.ok) {
                    throw new Error('HTTP error! status: ' + response.status);
                }
                return response.text().then(text => {
                    console.log('Response text:', text);
                    try {
                        return JSON.parse(text);
                    } catch (e) {
                        console.error('JSON parse error:', e);
                        console.error('Response was not JSON:', text);
                        throw new Error('Server returned invalid JSON: ' + text.substring(0, 100));
                    }
                });
            })
            .then(data => {
                console.log('Parsed response data:', data);
                if (data.status === 'success') {
                    alert(data.message);
                    location.reload();
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred while processing purchase: ' + error.message);
            });
        });

        // Edit purchase function
        function editPurchase(purchase) {
            // Fill form with purchase data
            document.querySelector('input[name="supplier_name"]').value = purchase.supplier_name;
            document.querySelector('input[name="supplier_contact"]').value = purchase.supplier_contact;
            document.querySelector('textarea[name="supplier_address"]').value = purchase.supplier_address;
            document.querySelector('input[name="product_name"]').value = purchase.product_name;
            document.querySelector('input[name="product_category"]').value = purchase.product_category || '';
            document.querySelector('input[name="sell_price"]').value = purchase.sell_price || purchase.purchase_price;
            document.querySelector('input[name="distributor"]').value = purchase.distributor || '';
            document.querySelector('input[name="hsn_code"]').value = purchase.hsn_code;
            document.querySelector('input[name="purchase_price"]').value = purchase.purchase_price;
            document.querySelector('input[name="quantity"]').value = purchase.quantity;
            document.querySelector('input[name="total_amount"]').value = purchase.total_amount;
            document.querySelector('input[name="bill_number"]').value = purchase.bill_number;
            document.querySelector('input[name="bill_date"]').value = purchase.bill_date;
            document.querySelector('select[name="payment_status"]').value = purchase.payment_status;
            document.querySelector('input[name="amount_paid"]').value = purchase.amount_paid;
            
            // Update payment fields based on the selected status
            updatePaymentFields();
            
            // Change form to update mode
            const form = document.getElementById('purchaseForm');
            form.innerHTML += '<input type="hidden" name="purchase_id" value="' + purchase.id + '">';
            form.querySelector('button[type="submit"]').innerHTML = '<i class="bx bx-edit"></i> Update Purchase';
            
            // Scroll to form
            form.scrollIntoView({ behavior: 'smooth' });
        }

        // Delete purchase function
        function deletePurchase(id) {
            if (confirm('Are you sure you want to delete this purchase?')) {
                const formData = new FormData();
                formData.append('action', 'delete_purchase');
                formData.append('id', id);
                
                fetch('', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        alert(data.message);
                        location.reload();
                    } else {
                        alert('Error: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('An error occurred while deleting purchase');
                });
            }
        }

        // View purchase function
        function viewPurchase(purchase) {
            // Calculate paid and pending amounts based on payment status
            let paidAmount, pendingAmount;
            if (purchase.payment_status == 'paid') {
                paidAmount = purchase.total_amount;
                pendingAmount = 0;
            } else {
                paidAmount = purchase.amount_paid;
                pendingAmount = purchase.total_amount - purchase.amount_paid;
            }
            const paymentStatusClass = purchase.payment_status == 'paid' ? 'success' : 'danger';
            
            const purchaseDetails = `
                <div class="row">
                    <div class="col-md-6">
                        <h6 class="text-primary">Supplier Information</h6>
                        <table class="table table-sm">
                            <tr>
                                <td><strong>Name:</strong></td>
                                <td>${purchase.supplier_name}</td>
                            </tr>
                            <tr>
                                <td><strong>Contact:</strong></td>
                                <td>${purchase.supplier_contact || 'N/A'}</td>
                            </tr>
                            <tr>
                                <td><strong>Address:</strong></td>
                                <td>${purchase.supplier_address || 'N/A'}</td>
                            </tr>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <h6 class="text-primary">Purchase Information</h6>
                        <table class="table table-sm">
                            <tr>
                                <td><strong>Purchase ID:</strong></td>
                                <td>#${purchase.id}</td>
                            </tr>
                            <tr>
                                <td><strong>Bill Number:</strong></td>
                                <td>${purchase.bill_number || 'N/A'}</td>
                            </tr>
                            <tr>
                                <td><strong>Bill Date:</strong></td>
                                <td>${new Date(purchase.bill_date).toLocaleDateString('en-IN')}</td>
                            </tr>
                            <tr>
                                <td><strong>Created:</strong></td>
                                <td>${new Date(purchase.created_at).toLocaleDateString('en-IN')}</td>
                            </tr>
                        </table>
                    </div>
                </div>
                
                <hr>
                
                <div class="row">
                    <div class="col-md-6">
                        <h6 class="text-primary">Product Details</h6>
                        <table class="table table-sm">
                            <tr>
                                <td><strong>Product Name:</strong></td>
                                <td>${purchase.product_name}</td>
                            </tr>
                            <tr>
                                <td><strong>HSN Code:</strong></td>
                                <td>${purchase.hsn_code || 'N/A'}</td>
                            </tr>
                            <tr>
                                <td><strong>Category:</strong></td>
                                <td>${purchase.product_category || 'N/A'}</td>
                            </tr>
                            <tr>
                                <td><strong>Distributor:</strong></td>
                                <td>${purchase.distributor || 'N/A'}</td>
                            </tr>
                            <tr>
                                <td><strong>Quantity:</strong></td>
                                <td>${purchase.quantity}</td>
                            </tr>
                            <tr>
                                <td><strong>Purchase Price:</strong></td>
                                <td>₹${parseFloat(purchase.purchase_price).toFixed(2)}</td>
                            </tr>
                            <tr>
                                <td><strong>Sell Price:</strong></td>
                                <td>₹${parseFloat(purchase.sell_price || 0).toFixed(2)}</td>
                            </tr>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <h6 class="text-primary">Payment Details</h6>
                        <table class="table table-sm">
                            <tr>
                                <td><strong>Total Amount:</strong></td>
                                <td class="fw-bold">₹${parseFloat(purchase.total_amount).toFixed(2)}</td>
                            </tr>
                            <tr>
                                <td><strong>Amount Paid:</strong></td>
                                <td class="text-success fw-bold">₹${parseFloat(paidAmount).toFixed(2)}</td>
                            </tr>
                            <tr>
                                <td><strong>Pending Amount:</strong></td>
                                <td class="text-danger fw-bold">₹${pendingAmount.toFixed(2)}</td>
                            </tr>
                            <tr>
                                <td><strong>Payment Status:</strong></td>
                                <td><span class="badge bg-${paymentStatusClass}">${purchase.payment_status.charAt(0).toUpperCase() + purchase.payment_status.slice(1)}</span></td>
                            </tr>
                        </table>
                    </div>
                </div>
                
                <div class="row mt-3">
                    <div class="col-12">
                        <div class="alert alert-info">
                            <strong>Payment Summary:</strong>
                            <ul class="mb-0 mt-2">
                                <li>Total Purchase Amount: ₹${parseFloat(purchase.total_amount).toFixed(2)}</li>
                                <li>Amount Paid: ₹${parseFloat(paidAmount).toFixed(2)}</li>
                                <li>Outstanding Balance: ₹${pendingAmount.toFixed(2)}</li>
                            </ul>
                        </div>
                    </div>
                </div>
                
                <div class="row mt-3">
                    <div class="col-12">
                        <h6 class="text-primary">Product Description</h6>
                        <div class="card">
                            <div class="card-body">
                                <p class="mb-0">${purchase.details || 'No additional details provided.'}</p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="row mt-3">
                    <div class="col-12">
                        <h6 class="text-primary">Product Images</h6>
                        <div class="row" id="productImages">
                            ${purchase.images && purchase.images.length > 0 ? 
                                purchase.images.map(image => `
                                    <div class="col-md-3 mb-3">
                                        <div class="card">
                                            <img src="uploads/${image}" class="card-img-top" style="height: 200px; object-fit: cover;" alt="Product Image" onclick="openImageModal('uploads/${image}')">
                                            <div class="card-body p-2">
                                                <small class="text-muted">${image}</small>
                                            </div>
                                        </div>
                                    </div>
                                `).join('') : 
                                '<div class="col-12"><div class="alert alert-warning">No images available for this product.</div></div>'
                            }
                        </div>
                    </div>
                </div>
            `;
            
            document.getElementById('purchaseDetails').innerHTML = purchaseDetails;
            document.getElementById('viewPurchaseModalLabel').textContent = `Purchase #${purchase.id} - ${purchase.supplier_name}`;
            
            // Store purchase data for printing
            window.currentPurchase = purchase;
            
            // Show modal
            const modal = new bootstrap.Modal(document.getElementById('viewPurchaseModal'));
            modal.show();
        }

        // Open image in full size modal
        function openImageModal(imageSrc) {
            const imageModal = `
                <div class="modal fade" id="imageModal" tabindex="-1">
                    <div class="modal-dialog modal-lg modal-dialog-centered">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">Product Image</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body text-center">
                                <img src="${imageSrc}" class="img-fluid" alt="Product Image" style="max-height: 70vh;">
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            // Remove existing image modal if any
            const existingModal = document.getElementById('imageModal');
            if (existingModal) {
                existingModal.remove();
            }
            
            // Add new modal to body
            document.body.insertAdjacentHTML('beforeend', imageModal);
            
            // Show modal
            $('#imageModal').modal('show');
        }

        // Print purchase function
        function printPurchase() {
            if (!window.currentPurchase) {
                alert('No purchase data available for printing');
                return;
            }
            
            const purchase = window.currentPurchase;
            // Calculate paid and pending amounts based on payment status
            let paidAmount, pendingAmount;
            if (purchase.payment_status == 'paid') {
                paidAmount = purchase.total_amount;
                pendingAmount = 0;
            } else {
                paidAmount = purchase.amount_paid;
                pendingAmount = purchase.total_amount - purchase.amount_paid;
            }
            
            const printContent = `
                <!DOCTYPE html>
                <html>
                <head>
                    <title>Purchase Invoice - #${purchase.id}</title>
                    <style>
                        body { font-family: Arial, sans-serif; margin: 20px; }
                        .header { text-align: center; border-bottom: 2px solid #333; padding-bottom: 20px; margin-bottom: 30px; }
                        .company-name { font-size: 24px; font-weight: bold; color: #333; }
                        .invoice-title { font-size: 18px; margin-top: 10px; }
                        .details-table { width: 100%; border-collapse: collapse; margin: 20px 0; }
                        .details-table th, .details-table td { border: 1px solid #ddd; padding: 8px; text-align: left; }
                        .details-table th { background-color: #f2f2f2; font-weight: bold; }
                        .amount-section { background-color: #f9f9f9; padding: 15px; margin: 20px 0; }
                        .total-amount { font-size: 18px; font-weight: bold; color: #333; }
                        .footer { margin-top: 30px; text-align: center; font-size: 12px; color: #666; }
                        @media print { body { margin: 0; } }
                    </style>
                </head>
                <body>
                    <div class="header">
                        <div class="company-name">Kumawat Computer</div>
                        <div class="invoice-title">Purchase Invoice</div>
                    </div>
                    
                    <table class="details-table">
                        <tr>
                            <th colspan="2">Supplier Information</th>
                            <th colspan="2">Purchase Information</th>
                        </tr>
                        <tr>
                            <td><strong>Supplier Name:</strong></td>
                            <td>${purchase.supplier_name}</td>
                            <td><strong>Purchase ID:</strong></td>
                            <td>#${purchase.id}</td>
                        </tr>
                        <tr>
                            <td><strong>Contact:</strong></td>
                            <td>${purchase.supplier_contact || 'N/A'}</td>
                            <td><strong>Bill Number:</strong></td>
                            <td>${purchase.bill_number || 'N/A'}</td>
                        </tr>
                        <tr>
                            <td><strong>Address:</strong></td>
                            <td>${purchase.supplier_address || 'N/A'}</td>
                            <td><strong>Bill Date:</strong></td>
                            <td>${new Date(purchase.bill_date).toLocaleDateString('en-IN')}</td>
                        </tr>
                    </table>
                    
                    <table class="details-table">
                        <tr>
                            <th colspan="4">Product Details</th>
                        </tr>
                        <tr>
                            <td><strong>Product Name:</strong></td>
                            <td>${purchase.product_name}</td>
                            <td><strong>HSN Code:</strong></td>
                            <td>${purchase.hsn_code || 'N/A'}</td>
                        </tr>
                        <tr>
                            <td><strong>Quantity:</strong></td>
                            <td>${purchase.quantity}</td>
                            <td><strong>Unit Price:</strong></td>
                            <td>₹${parseFloat(purchase.purchase_price).toFixed(2)}</td>
                        </tr>
                    </table>
                    
                    <div class="amount-section">
                        <table class="details-table">
                            <tr>
                                <th>Payment Details</th>
                                <th>Amount (₹)</th>
                            </tr>
                            <tr>
                                <td><strong>Total Purchase Amount:</strong></td>
                                <td class="total-amount">₹${parseFloat(purchase.total_amount).toFixed(2)}</td>
                            </tr>
                            <tr>
                                <td><strong>Amount Paid:</strong></td>
                                <td>₹${parseFloat(paidAmount).toFixed(2)}</td>
                            </tr>
                            <tr>
                                <td><strong>Pending Amount:</strong></td>
                                <td>₹${pendingAmount.toFixed(2)}</td>
                            </tr>
                            <tr>
                                <td><strong>Payment Status:</strong></td>
                                <td>${purchase.payment_status.charAt(0).toUpperCase() + purchase.payment_status.slice(1)}</td>
                            </tr>
                        </table>
                    </div>
                    
                    <div class="footer">
                        <p>Generated on: ${new Date().toLocaleDateString('en-IN')} at ${new Date().toLocaleTimeString('en-IN')}</p>
                        <p>Thank you for your business!</p>
                    </div>
                </body>
                </html>
            `;
            
            const printWindow = window.open('', '_blank');
            printWindow.document.write(printContent);
            printWindow.document.close();
            printWindow.focus();
            printWindow.print();
            printWindow.close();
        }

        // Simple image handling - no preview needed

        // Initialize DataTable
        $(document).ready(function() {
            $('#purchaseTable').DataTable({
                "pageLength": 10,
                "order": [[0, "desc"]]
            });
            
            // Initialize image uploadify with configuration (matching ecommerce-add-new-products.php)
            $('#image-uploadify').imageuploadify({
                'auto': false,  // Disable auto upload
                'multi': true,  // Allow multiple files
                'maxFiles': 10, // Maximum 10 files
                'maxFileSize': '10MB', // Maximum file size
                'allowedExtensions': ['jpg', 'jpeg', 'png'], // Allowed extensions
                'onUpload': function(files) {
                    console.log('Uploadify files:', files);
                }
            });
        });
    </script>
</body>
</html>
