<?php
session_start();
require_once '../assets/db_connect.php';
//require_once '../../includes/auth.php';
//requireLogin('admin', 'pharmacist');

// Check if user is logged in
if (!isset($_SESSION['user']) || empty($_SESSION['user']['id'])) {
    header('Location: ../../login.php');
    exit();
}

$user = $_SESSION['user'];
$user_id = $user['id'];
$user_role = $user['role'];
$shop_id = $user['shop_id'];

$purchase_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$purchase_id) {
    $_SESSION['error'] = "Invalid purchase ID.";
    header('Location: purchases.php');
    exit();
}

// Initialize messages
$error_message = '';
$success_message = '';

// Check if there are session messages from previous redirect
if (isset($_SESSION['error'])) {
    $error_message = $_SESSION['error'];
    unset($_SESSION['error']);
}

if (isset($_SESSION['success'])) {
    $success_message = $_SESSION['success'];
    unset($_SESSION['success']);
}

// Fetch purchase details
$purchase = null;
try {
    // Check if user has access to this purchase (admin or same shop)
    $stmt = $pdo->prepare("
        SELECT p.*, s.name as supplier_name, u.fullname as created_by_name, 
               sh.name as shop_name, sh.id as shop_id
        FROM purchases p
        LEFT JOIN suppliers s ON p.supplier_id = s.id
        LEFT JOIN users u ON p.created_by = u.id
        LEFT JOIN shops sh ON p.shop_id = sh.id
        WHERE p.id = ?
    ");
    $stmt->execute([$purchase_id]);
    $purchase = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$purchase) {
        $_SESSION['error'] = "Purchase not found.";
        header('Location: purchases.php');
        exit();
    }
    
    // Check if user has permission to edit this purchase
    if ($user_role !== 'admin' && $purchase['shop_id'] != $shop_id) {
        $_SESSION['error'] = "You don't have permission to edit this purchase.";
        header('Location: purchases.php');
        exit();
    }
} catch (PDOException $e) {
    $_SESSION['error'] = "Database error: " . $e->getMessage();
    header('Location: purchases.php');
    exit();
}

// Fetch purchase lines with product details
$purchase_lines = [];
try {
    $stmt = $pdo->prepare("
        SELECT pl.*, pb.batch_no, pb.expiry_date, pb.cost_price as current_cost_price,
               pb.sell_price as current_sell_price, pb.qty as current_stock,
               pr.name as product_name, pr.sku as product_sku,
               pr.id as product_id
        FROM purchase_lines pl
        JOIN product_batches pb ON pl.batch_id = pb.id
        JOIN products pr ON pb.product_id = pr.id
        WHERE pl.purchase_id = ?
        ORDER BY pl.id
    ");
    $stmt->execute([$purchase_id]);
    $purchase_lines = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $error_message = "Failed to load purchase items: " . $e->getMessage();
}

// Fetch all suppliers for dropdown
$suppliers = [];
try {
    $stmt = $pdo->prepare("SELECT id, name FROM suppliers ORDER BY name");
    $stmt->execute();
    $suppliers = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $error_message = "Failed to load suppliers: " . $e->getMessage();
}

// Fetch all active batches for the current shop
$batches = [];
try {
    // If admin, show all batches from purchase's shop, otherwise only user's shop
    $shop_filter = $purchase['shop_id'];
    
    $stmt = $pdo->prepare("
        SELECT pb.id, pb.batch_no, pb.expiry_date, pb.cost_price, pb.sell_price,
               pb.qty as current_stock, p.name as product_name, p.sku as product_sku,
               CONCAT(p.name, ' - ', pb.batch_no, ' (Exp: ', DATE_FORMAT(pb.expiry_date, '%Y-%m-%d'), ')') as display_text
        FROM product_batches pb
        JOIN products p ON pb.product_id = p.id
        WHERE pb.shop_id = ? AND pb.is_active = 1
        ORDER BY p.name, pb.expiry_date
    ");
    $stmt->execute([$shop_filter]);
    $batches = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $error_message = "Failed to load batches: " . $e->getMessage();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $pdo->beginTransaction();
        
        // Get form data
        $supplier_id = isset($_POST['supplier_id']) ? intval($_POST['supplier_id']) : null;
        $invoice_no = trim($_POST['invoice_no'] ?? '');
        $purchase_date = $_POST['purchase_date'] ?? date('Y-m-d');
        $items = $_POST['items'] ?? [];
        
        // Validate required fields
        if (empty($supplier_id)) {
            throw new Exception("Supplier is required.");
        }
        
        if (empty($invoice_no)) {
            throw new Exception("Invoice number is required.");
        }
        
        if (empty($items)) {
            throw new Exception("At least one item is required.");
        }
        
        // Validate items
        $valid_items = [];
        $total_amount = 0;
        
        foreach ($items as $index => $item) {
            $batch_id = intval($item['batch_id'] ?? 0);
            $qty = intval($item['qty'] ?? 0);
            $cost_price = floatval($item['cost_price'] ?? 0);
            
            if ($batch_id <= 0 || $qty <= 0 || $cost_price <= 0) {
                continue; // Skip invalid items
            }
            
            // Check if batch exists and belongs to the correct shop
            $batch_stmt = $pdo->prepare("
                SELECT pb.id, pb.product_id, pb.qty, pb.shop_id 
                FROM product_batches pb 
                WHERE pb.id = ? AND pb.is_active = 1
            ");
            $batch_stmt->execute([$batch_id]);
            $batch = $batch_stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$batch) {
                throw new Exception("Invalid batch selected at item " . ($index + 1));
            }
            
            // Check if batch belongs to the same shop as purchase
            if ($batch['shop_id'] != $purchase['shop_id']) {
                throw new Exception("Batch does not belong to this shop at item " . ($index + 1));
            }
            
            $valid_items[] = [
                'batch_id' => $batch_id,
                'qty' => $qty,
                'cost_price' => $cost_price,
                'product_id' => $batch['product_id']
            ];
            
            $total_amount += ($qty * $cost_price);
        }
        
        if (empty($valid_items)) {
            throw new Exception("No valid items found.");
        }
        
        // First, reverse the old inventory movements
        foreach ($purchase_lines as $old_item) {
            // Create reverse inventory movement
            $reverse_stmt = $pdo->prepare("
                INSERT INTO inventory_movements 
                (product_id, batch_id, change_qty, movement_type, note, created_by, shop_id)
                VALUES (?, ?, ?, 'ADJUSTMENT', ?, ?, ?)
            ");
            $reverse_stmt->execute([
                $old_item['product_id'],
                $old_item['batch_id'],
                $old_item['qty'],
                "Reversed for editing purchase #{$purchase_id}",
                $user_id,
                $purchase['shop_id']
            ]);
        }
        
        // Delete old purchase lines
        $delete_stmt = $pdo->prepare("DELETE FROM purchase_lines WHERE purchase_id = ?");
        $delete_stmt->execute([$purchase_id]);
        
        // Update purchase header
        $update_stmt = $pdo->prepare("
            UPDATE purchases 
            SET supplier_id = ?, invoice_no = ?, purchase_date = ?, 
                total = ?, updated_by = ?
            WHERE id = ?
        ");
        $update_stmt->execute([
            $supplier_id,
            $invoice_no,
            $purchase_date,
            $total_amount,
            $user_id,
            $purchase_id
        ]);
        
        // Insert new purchase lines and create inventory movements
        foreach ($valid_items as $item) {
            // Insert purchase line
            $line_stmt = $pdo->prepare("
                INSERT INTO purchase_lines (purchase_id, batch_id, qty, cost_price)
                VALUES (?, ?, ?, ?)
            ");
            $line_stmt->execute([
                $purchase_id,
                $item['batch_id'],
                $item['qty'],
                $item['cost_price']
            ]);
            
            // Create inventory movement for purchase
            $movement_stmt = $pdo->prepare("
                INSERT INTO inventory_movements 
                (product_id, batch_id, change_qty, movement_type, reference_id, created_by, shop_id)
                VALUES (?, ?, ?, 'PURCHASE', ?, ?, ?)
            ");
            $movement_stmt->execute([
                $item['product_id'],
                $item['batch_id'],
                $item['qty'],
                $purchase_id,
                $user_id,
                $purchase['shop_id']
            ]);
        }
        
        $pdo->commit();
        
        // Set success message and redirect
        $_SESSION['success'] = "Purchase updated successfully!";
        header('Location: edit_purchase.php?id=' . $purchase_id);
        exit();
        
    } catch (Exception $e) {
        $pdo->rollBack();
        $error_message = "Error: " . $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Purchase - Pharmacy System</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">
    <style>
        :root {
            --primary-color: #4361ee;
            --success-color: #06d6a0;
            --danger-color: #ef476f;
            --warning-color: #ffd166;
            --info-color: #118ab2;
        }
        
        .batch-info {
            background-color: #f8f9fa;
            padding: 10px;
            border-radius: 8px;
            margin-bottom: 10px;
            border-left: 4px solid var(--info-color);
        }
        
        .item-row {
            background-color: #fff;
            border: 1px solid #e0e0e0;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
            transition: all 0.3s ease;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        
        .item-row:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            border-color: var(--primary-color);
        }
        
        .remove-item {
            color: var(--danger-color);
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .remove-item:hover {
            color: #d00000;
            transform: scale(1.1);
        }
        
        .total-section {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-top: 20px;
        }
        
        .batch-select {
            max-height: 300px;
            overflow-y: auto;
        }
        
        .expired {
            color: var(--danger-color);
            font-weight: bold;
            background-color: rgba(239, 71, 111, 0.1);
        }
        
        .expiring-soon {
            color: var(--warning-color);
            font-weight: bold;
            background-color: rgba(255, 209, 102, 0.1);
        }
        
        .user-info {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 12px;
            border-radius: 10px;
            margin-bottom: 20px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        .alert-custom {
            border-radius: 10px;
            border: none;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .alert-success-custom {
            background: linear-gradient(135deg, #06d6a0 0%, #04a17e 100%);
            color: white;
            border-left: 5px solid #049669;
        }
        
        .alert-danger-custom {
            background: linear-gradient(135deg, #ef476f 0%, #d43a5c 100%);
            color: white;
            border-left: 5px solid #c93454;
        }
        
        .alert-info-custom {
            background: linear-gradient(135deg, #118ab2 0%, #0d6e8e 100%);
            color: white;
            border-left: 5px solid #0b5e7a;
        }
        
        .card-header-custom {
            background: linear-gradient(135deg, #4361ee 0%, #3a56d4 100%);
            color: white;
            border-radius: 10px 10px 0 0 !important;
            padding: 15px 20px;
        }
        
        .btn-success-custom {
            background: linear-gradient(135deg, #06d6a0 0%, #049669 100%);
            border: none;
            color: white;
            transition: all 0.3s ease;
        }
        
        .btn-success-custom:hover {
            background: linear-gradient(135deg, #049669 0%, #037454 100%);
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(6, 214, 160, 0.3);
        }
        
        .btn-primary-custom {
            background: linear-gradient(135deg, #4361ee 0%, #3a56d4 100%);
            border: none;
            color: white;
            transition: all 0.3s ease;
        }
        
        .btn-primary-custom:hover {
            background: linear-gradient(135deg, #3a56d4 0%, #314bc0 100%);
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(67, 97, 238, 0.3);
        }
        
        .input-group-text-custom {
            background-color: #f8f9fa;
            border: 1px solid #ced4da;
            color: #495057;
        }
        
        .line-total {
            color: var(--success-color);
            font-weight: bold;
            font-size: 1.1em;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.25rem rgba(67, 97, 238, 0.25);
        }
        
        .pulse-animation {
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0% {
                box-shadow: 0 0 0 0 rgba(6, 214, 160, 0.4);
            }
            70% {
                box-shadow: 0 0 0 10px rgba(6, 214, 160, 0);
            }
            100% {
                box-shadow: 0 0 0 0 rgba(6, 214, 160, 0);
            }
        }
        
        .fade-in {
            animation: fadeIn 0.5s ease-in;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .sticky-actions {
            position: sticky;
            bottom: 20px;
            background: white;
            padding: 15px;
            border-radius: 10px;
            box-shadow: 0 -4px 12px rgba(0,0,0,0.1);
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <?php 
    // Check if header file exists and includes user session
    $header_file = '../includes/header.php';
    if (file_exists($header_file)) {
        include $header_file;
    } else {
        // Simple header if file doesn't exist
        echo '<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
            <div class="container-fluid">
                <a class="navbar-brand" href="#">
                    <i class="fas fa-prescription-bottle-alt"></i> Pharmacy System
                </a>
                <div class="navbar-text text-light">
                    <i class="fas fa-user-circle"></i> ' . htmlspecialchars($user['fullname']) . ' 
                    <span class="badge bg-info">' . $user['role'] . '</span>
                </div>
            </div>
        </nav>';
    }
    ?>
    
    <div class="container-fluid">
        <div class="row">
            <?php 
            // Check if sidebar file exists
            $sidebar_file = '../includes/sidebar.php';
			
            if (file_exists($sidebar_file)) {
                include $sidebar_file;
            }
            ?>
            
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">
                        <i class="fas fa-edit text-primary"></i> Edit Purchase
                        <small class="text-muted">#<?php echo $purchase_id; ?></small>
                    </h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a href="purchases.php" class="btn btn-outline-secondary">
                            <i class="fas fa-arrow-left"></i> Back to Purchases
                        </a>
                    </div>
                </div>
                
                <!-- User info box -->
                <div class="user-info fade-in">
                    <div class="row">
                        <div class="col-md-4">
                            <strong><i class="fas fa-store"></i> Shop:</strong> 
                            <?php echo htmlspecialchars($user['shop_name'] ?? 'N/A'); ?>
                        </div>
                        <div class="col-md-4">
                            <strong><i class="fas fa-user"></i> User:</strong> 
                            <?php echo htmlspecialchars($user['fullname']); ?> 
                            <span class="badge bg-light text-dark"><?php echo $user['role']; ?></span>
                        </div>
                        <div class="col-md-4">
                            <strong><i class="fas fa-calendar-alt"></i> Last Updated:</strong> 
                            <?php echo date('M d, Y H:i:s'); ?>
                        </div>
                    </div>
                </div>
                
                <!-- Success Alert -->
                <?php if (!empty($success_message)): ?>
                <div class="alert alert-success-custom alert-custom animate__animated animate__fadeInDown" role="alert">
                    <div class="d-flex align-items-center">
                        <i class="fas fa-check-circle fa-2x me-3"></i>
                        <div>
                            <h5 class="alert-heading mb-1"><i class="fas fa-thumbs-up"></i> Success!</h5>
                            <?php echo $success_message; ?>
                        </div>
                        <button type="button" class="btn-close btn-close-white ms-auto" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <div class="progress mt-2" style="height: 3px;">
                        <div class="progress-bar bg-light" role="progressbar" style="width: 100%" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- Error Alert -->
                <?php if (!empty($error_message)): ?>
                <div class="alert alert-danger-custom alert-custom animate__animated animate__shakeX" role="alert">
                    <div class="d-flex align-items-center">
                        <i class="fas fa-exclamation-triangle fa-2x me-3"></i>
                        <div>
                            <h5 class="alert-heading mb-1"><i class="fas fa-exclamation-circle"></i> Error!</h5>
                            <?php echo $error_message; ?>
                        </div>
                        <button type="button" class="btn-close btn-close-white ms-auto" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <div class="progress mt-2" style="height: 3px;">
                        <div class="progress-bar bg-light" role="progressbar" style="width: 100%" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- Info Alert for Instructions -->
                <div class="alert alert-info-custom alert-custom fade-in">
                    <div class="d-flex align-items-center">
                        <i class="fas fa-info-circle fa-2x me-3"></i>
                        <div>
                            <h5 class="alert-heading mb-1"><i class="fas fa-lightbulb"></i> Important Notes</h5>
                            <ul class="mb-0 ps-3">
                                <li>Editing a purchase will reverse old inventory movements and create new ones</li>
                                <li>Make sure all batch selections are valid and belong to this shop</li>
                                <li>Expired batches are marked in red, expiring soon in yellow</li>
                                <li>All changes are logged for audit purposes</li>
                            </ul>
                        </div>
                    </div>
                </div>
                
                <form method="POST" action="" id="editPurchaseForm">
                    <div class="row fade-in">
                        <div class="col-md-6">
                            <div class="card mb-4 border-0 shadow">
                                <div class="card-header-custom">
                                    <h5 class="mb-0"><i class="fas fa-info-circle me-2"></i> Purchase Information</h5>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label for="invoice_no" class="form-label fw-bold">
                                            <i class="fas fa-file-invoice text-primary"></i> Invoice Number *
                                        </label>
                                        <div class="input-group">
                                            <span class="input-group-text input-group-text-custom">
                                                <i class="fas fa-file-invoice-dollar"></i>
                                            </span>
                                            <input type="text" class="form-control" id="invoice_no" name="invoice_no" 
                                                   value="<?php echo htmlspecialchars($purchase['invoice_no']); ?>" required
                                                   placeholder="Enter invoice number">
                                        </div>
                                        <small class="text-muted">Unique identifier for this purchase</small>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label for="purchase_date" class="form-label fw-bold">
                                                    <i class="fas fa-calendar text-primary"></i> Purchase Date *
                                                </label>
                                                <div class="input-group">
                                                    <span class="input-group-text input-group-text-custom">
                                                        <i class="fas fa-calendar-alt"></i>
                                                    </span>
                                                    <input type="date" class="form-control" id="purchase_date" 
                                                           name="purchase_date" value="<?php echo $purchase['purchase_date']; ?>" required>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label for="supplier_id" class="form-label fw-bold">
                                                    <i class="fas fa-truck text-primary"></i> Supplier *
                                                </label>
                                                <div class="input-group">
                                                    <span class="input-group-text input-group-text-custom">
                                                        <i class="fas fa-user-tie"></i>
                                                    </span>
                                                    <select class="form-select" id="supplier_id" name="supplier_id" required>
                                                        <option value="">Select Supplier</option>
                                                        <?php foreach ($suppliers as $supplier): ?>
                                                            <option value="<?php echo $supplier['id']; ?>" 
                                                                <?php echo ($supplier['id'] == $purchase['supplier_id']) ? 'selected' : ''; ?>>
                                                                <?php echo htmlspecialchars($supplier['name']); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label fw-bold">
                                            <i class="fas fa-store text-primary"></i> Shop
                                        </label>
                                        <div class="input-group">
                                            <span class="input-group-text input-group-text-custom">
                                                <i class="fas fa-building"></i>
                                            </span>
                                            <input type="text" class="form-control bg-light" value="<?php echo htmlspecialchars($purchase['shop_name']); ?>" readonly>
                                        </div>
                                        <input type="hidden" name="shop_id" value="<?php echo $purchase['shop_id']; ?>">
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label fw-bold">
                                                    <i class="fas fa-money-bill-wave text-primary"></i> Original Total
                                                </label>
                                                <div class="input-group">
                                                    <span class="input-group-text input-group-text-custom">
                                                        <i class="fas fa-dollar-sign"></i>
                                                    </span>
                                                    <input type="text" class="form-control fw-bold text-success" 
                                                           value="<?php echo number_format($purchase['total'], 2); ?>" readonly>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label fw-bold">
                                                    <i class="fas fa-user text-primary"></i> Created By
                                                </label>
                                                <div class="input-group">
                                                    <span class="input-group-text input-group-text-custom">
                                                        <i class="fas fa-user-edit"></i>
                                                    </span>
                                                    <input type="text" class="form-control" 
                                                           value="<?php echo htmlspecialchars($purchase['created_by_name']); ?>" readonly>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="card mb-4 border-0 shadow">
                                <div class="card-header-custom d-flex justify-content-between align-items-center">
                                    <h5 class="mb-0"><i class="fas fa-shopping-cart me-2"></i> Purchase Items</h5>
                                    <button type="button" class="btn btn-light btn-sm pulse-animation" id="addItemBtn">
                                        <i class="fas fa-plus-circle me-1"></i> Add Item
                                    </button>
                                </div>
                                <div class="card-body">
                                    <div id="itemsContainer">
                                        <?php if (empty($purchase_lines)): ?>
                                            <div class="alert alert-warning alert-custom">
                                                <div class="d-flex align-items-center">
                                                    <i class="fas fa-exclamation-triangle fa-2x me-3"></i>
                                                    <div>
                                                        <h5 class="alert-heading mb-1">No Items Found</h5>
                                                        <p class="mb-0">This purchase doesn't have any items. Click "Add Item" to start.</p>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php else: ?>
                                            <?php foreach ($purchase_lines as $index => $item): ?>
                                                <div class="item-row fade-in" data-index="<?php echo $index; ?>">
                                                    <div class="row">
                                                        <div class="col-md-5">
                                                            <div class="mb-3">
                                                                <label class="form-label fw-bold">
                                                                    <i class="fas fa-box text-primary"></i> Product & Batch *
                                                                </label>
                                                                <select class="form-select batch-select" name="items[<?php echo $index; ?>][batch_id]" required>
                                                                    <option value="">Select Product Batch</option>
                                                                    <?php foreach ($batches as $batch): 
                                                                        $expiry_class = '';
                                                                        $expiry_date = new DateTime($batch['expiry_date']);
                                                                        $today = new DateTime();
                                                                        $diff = $today->diff($expiry_date);
                                                                        
                                                                        if ($expiry_date < $today) {
                                                                            $expiry_class = 'expired';
                                                                        } elseif ($diff->days <= 30) {
                                                                            $expiry_class = 'expiring-soon';
                                                                        }
                                                                    ?>
                                                                        <option value="<?php echo $batch['id']; ?>" 
                                                                            data-cost-price="<?php echo $batch['cost_price']; ?>"
                                                                            data-sell-price="<?php echo $batch['sell_price']; ?>"
                                                                            data-current-stock="<?php echo $batch['current_stock']; ?>"
                                                                            data-expiry-date="<?php echo $batch['expiry_date']; ?>"
                                                                            <?php echo ($batch['id'] == $item['batch_id']) ? 'selected' : ''; ?>
                                                                            class="<?php echo $expiry_class; ?>">
                                                                            <?php echo htmlspecialchars($batch['display_text']); ?>
                                                                            <?php if ($expiry_class): ?>
                                                                                (<?php echo ucfirst(str_replace('-', ' ', $expiry_class)); ?>)
                                                                            <?php endif; ?>
                                                                        </option>
                                                                    <?php endforeach; ?>
                                                                </select>
                                                                <div class="batch-details mt-2">
                                                                    <?php if ($item['batch_id']): ?>
                                                                        <div class="d-flex flex-wrap gap-2">
                                                                            <span class="badge bg-light text-dark">
                                                                                <i class="fas fa-dollar-sign text-success me-1"></i>
                                                                                <?php echo number_format($item['current_cost_price'], 2); ?>
                                                                            </span>
                                                                            <span class="badge bg-light text-dark">
                                                                                <i class="fas fa-tag text-warning me-1"></i>
                                                                                <?php echo number_format($item['current_sell_price'], 2); ?>
                                                                            </span>
                                                                            <span class="badge bg-light text-dark">
                                                                                <i class="fas fa-box text-info me-1"></i>
                                                                                <?php echo $item['current_stock']; ?> in stock
                                                                            </span>
                                                                        </div>
                                                                    <?php endif; ?>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="col-md-2">
                                                            <div class="mb-3">
                                                                <label class="form-label fw-bold">
                                                                    <i class="fas fa-hashtag text-primary"></i> Quantity *
                                                                </label>
                                                                <input type="number" class="form-control qty-input" 
                                                                       name="items[<?php echo $index; ?>][qty]" min="1" 
                                                                       value="<?php echo $item['qty']; ?>" required
                                                                       placeholder="Qty">
                                                            </div>
                                                        </div>
                                                        <div class="col-md-3">
                                                            <div class="mb-3">
                                                                <label class="form-label fw-bold">
                                                                    <i class="fas fa-money-bill text-primary"></i> Cost Price *
                                                                </label>
                                                                <div class="input-group">
                                                                    <span class="input-group-text input-group-text-custom">
                                                                        <i class="fas fa-dollar-sign"></i>
                                                                    </span>
                                                                    <input type="number" class="form-control cost-price-input" 
                                                                           name="items[<?php echo $index; ?>][cost_price]" 
                                                                           step="0.01" min="0.01" 
                                                                           value="<?php echo $item['cost_price']; ?>" required
                                                                           placeholder="0.00">
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="col-md-2">
                                                            <div class="mb-3">
                                                                <label class="form-label fw-bold">
                                                                    <i class="fas fa-trash text-primary"></i> Action
                                                                </label>
                                                                <button type="button" class="btn btn-outline-danger remove-item w-100 h-100" 
                                                                        title="Remove Item" data-bs-toggle="tooltip">
                                                                    <i class="fas fa-trash-alt"></i> Remove
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="row">
                                                        <div class="col-md-12">
                                                            <div class="item-total text-end pt-2 border-top">
                                                                <h5 class="mb-0">
                                                                    <i class="fas fa-calculator text-primary me-2"></i>
                                                                    Line Total: 
                                                                    <span class="line-total">Tsh<?php echo number_format($item['qty'] * $item['cost_price'], 2); ?></span>
                                                                </h5>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <div class="total-section fade-in">
                                        <div class="row align-items-center">
                                            <div class="col-md-6">
                                                <h4 class="mb-0">
                                                    <i class="fas fa-file-invoice-dollar me-2"></i> Grand Total
                                                </h4>
                                                <small class="opacity-75">Sum of all line totals</small>
                                            </div>
                                            <div class="col-md-6 text-end">
                                                <h2 class="mb-0">
                                                    Tsh<span id="grandTotal"><?php echo number_format($purchase['total'], 2); ?></span>
                                                </h2>
                                                <small class="opacity-75">Updated in real-time</small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Sticky Action Buttons -->
                    <div class="sticky-actions fade-in">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <a href="purchases.php" class="btn btn-outline-secondary">
                                    <i class="fas fa-times me-1"></i> Cancel
                                </a>
                                <button type="button" class="btn btn-info" onclick="validateForm()">
                                    <i class="fas fa-check me-1"></i> Validate Form
                                </button>
                            </div>
                            <div>
                                <button type="submit" class="btn btn-success-custom btn-lg">
                                    <i class="fas fa-save me-1"></i> Update Purchase
                                </button>
                            </div>
                        </div>
                    </div>
                </form>
            </main>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize Bootstrap tooltips
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
            var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl);
            });
            
            // Initialize date picker
            flatpickr("#purchase_date", {
                dateFormat: "Y-m-d",
                maxDate: "today"
            });
            
            let itemCounter = <?php echo count($purchase_lines); ?>;
            
            // Add new item
            document.getElementById('addItemBtn').addEventListener('click', function() {
                const container = document.getElementById('itemsContainer');
                const template = getItemTemplate(itemCounter);
                const tempDiv = document.createElement('div');
                tempDiv.innerHTML = template;
                
                // Add fade-in animation
                tempDiv.firstElementChild.classList.add('animate__animated', 'animate__fadeInUp');
                
                container.appendChild(tempDiv.firstElementChild);
                itemCounter++;
                updateGrandTotal();
                
                // Scroll to new item
                container.lastElementChild.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            });
            
            // Remove item with animation
            document.addEventListener('click', function(e) {
                if (e.target.closest('.remove-item')) {
                    const itemRow = e.target.closest('.item-row');
                    if (document.querySelectorAll('.item-row').length > 1) {
                        // Add fade-out animation
                        itemRow.classList.add('animate__animated', 'animate__fadeOutDown');
                        
                        setTimeout(() => {
                            itemRow.remove();
                            updateGrandTotal();
                            
                            // Show notification
                            showNotification('Item removed successfully!', 'warning');
                        }, 300);
                    } else {
                        showNotification('At least one item is required!', 'danger');
                    }
                }
            });
            
            // Update line total when quantity or price changes
            document.addEventListener('input', function(e) {
                if (e.target.classList.contains('qty-input') || e.target.classList.contains('cost-price-input')) {
                    const itemRow = e.target.closest('.item-row');
                    updateLineTotal(itemRow);
                    updateGrandTotal();
                }
            });
            
            // Update batch details when batch selection changes
            document.addEventListener('change', function(e) {
                if (e.target.classList.contains('batch-select')) {
                    const itemRow = e.target.closest('.item-row');
                    const selectedOption = e.target.options[e.target.selectedIndex];
                    const costPrice = selectedOption.getAttribute('data-cost-price');
                    const sellPrice = selectedOption.getAttribute('data-sell-price');
                    const currentStock = selectedOption.getAttribute('data-current-stock');
                    const expiryDate = selectedOption.getAttribute('data-expiry-date');
                    
                    if (costPrice) {
                        const costInput = itemRow.querySelector('.cost-price-input');
                        costInput.value = parseFloat(costPrice).toFixed(2);
                        costInput.setAttribute('data-original-price', costPrice);
                        
                        // Add animation to price update
                        costInput.classList.add('animate__animated', 'animate__pulse');
                        setTimeout(() => {
                            costInput.classList.remove('animate__animated', 'animate__pulse');
                        }, 500);
                    }
                    
                    // Update batch details display
                    const detailsDiv = itemRow.querySelector('.batch-details');
                    if (detailsDiv) {
                        detailsDiv.innerHTML = `
                            <div class="d-flex flex-wrap gap-2">
                                <span class="badge bg-light text-dark">
                                    <i class="fas fa-dollar-sign text-success me-1"></i>
                                    ${parseFloat(costPrice).toFixed(2)}
                                </span>
                                <span class="badge bg-light text-dark">
                                    <i class="fas fa-tag text-warning me-1"></i>
                                    ${parseFloat(sellPrice).toFixed(2)}
                                </span>
                                <span class="badge bg-light text-dark">
                                    <i class="fas fa-box text-info me-1"></i>
                                    ${currentStock} in stock
                                </span>
                                <span class="badge bg-light text-dark">
                                    <i class="fas fa-calendar text-primary me-1"></i>
                                    ${expiryDate}
                                </span>
                            </div>
                        `;
                    }
                    
                    // Highlight if batch is expired or expiring soon
                    if (selectedOption.classList.contains('expired')) {
                        showNotification('Selected batch is expired! Please verify.', 'danger');
                    } else if (selectedOption.classList.contains('expiring-soon')) {
                        showNotification('Selected batch is expiring soon!', 'warning');
                    }
                    
                    updateLineTotal(itemRow);
                    updateGrandTotal();
                }
            });
            
            // Form submission validation
            document.getElementById('editPurchaseForm').addEventListener('submit', function(e) {
                if (!validateForm()) {
                    e.preventDefault();
                } else {
                    // Show loading state
                    const submitBtn = this.querySelector('button[type="submit"]');
                    const originalText = submitBtn.innerHTML;
                    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> Updating...';
                    submitBtn.disabled = true;
                    
                    // Add loading animation to form
                    this.classList.add('animate__animated', 'animate__pulse');
                }
            });
            
            function getItemTemplate(index) {
                return `
                    <div class="item-row" data-index="${index}">
                        <div class="row">
                            <div class="col-md-5">
                                <div class="mb-3">
                                    <label class="form-label fw-bold">
                                        <i class="fas fa-box text-primary"></i> Product & Batch *
                                    </label>
                                    <select class="form-select batch-select" name="items[${index}][batch_id]" required>
                                        <option value="">Select Product Batch</option>
                                        <?php foreach ($batches as $batch): 
                                            $expiry_class = '';
                                            $expiry_date = new DateTime($batch['expiry_date']);
                                            $today = new DateTime();
                                            $diff = $today->diff($expiry_date);
                                            
                                            if ($expiry_date < $today) {
                                                $expiry_class = 'expired';
                                            } elseif ($diff->days <= 30) {
                                                $expiry_class = 'expiring-soon';
                                            }
                                        ?>
                                            <option value="<?php echo $batch['id']; ?>"
                                                data-cost-price="<?php echo $batch['cost_price']; ?>"
                                                data-sell-price="<?php echo $batch['sell_price']; ?>"
                                                data-current-stock="<?php echo $batch['current_stock']; ?>"
                                                data-expiry-date="<?php echo $batch['expiry_date']; ?>"
                                                class="<?php echo $expiry_class; ?>">
                                                <?php echo htmlspecialchars($batch['display_text']); ?>
                                                <?php if ($expiry_class): ?>
                                                    (<?php echo ucfirst(str_replace('-', ' ', $expiry_class)); ?>)
                                                <?php endif; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <div class="batch-details mt-2"></div>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="mb-3">
                                    <label class="form-label fw-bold">
                                        <i class="fas fa-hashtag text-primary"></i> Quantity *
                                    </label>
                                    <input type="number" class="form-control qty-input" 
                                           name="items[${index}][qty]" min="1" value="1" required
                                           placeholder="Qty">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="mb-3">
                                    <label class="form-label fw-bold">
                                        <i class="fas fa-money-bill text-primary"></i> Cost Price *
                                    </label>
                                    <div class="input-group">
                                        <span class="input-group-text input-group-text-custom">
                                            <i class="fas fa-dollar-sign"></i>
                                        </span>
                                        <input type="number" class="form-control cost-price-input" 
                                               name="items[${index}][cost_price]" step="0.01" min="0.01" required
                                               placeholder="0.00">
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="mb-3">
                                    <label class="form-label fw-bold">
                                        <i class="fas fa-trash text-primary"></i> Action
                                    </label>
                                    <button type="button" class="btn btn-outline-danger remove-item w-100 h-100" 
                                            title="Remove Item" data-bs-toggle="tooltip">
                                        <i class="fas fa-trash-alt"></i> Remove
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <div class="item-total text-end pt-2 border-top">
                                    <h5 class="mb-0">
                                        <i class="fas fa-calculator text-primary me-2"></i>
                                        Line Total: 
                                        <span class="line-total">Tsh0.00</span>
                                    </h5>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            }
            
            function updateLineTotal(itemRow) {
                const qtyInput = itemRow.querySelector('.qty-input');
                const costInput = itemRow.querySelector('.cost-price-input');
                const lineTotalSpan = itemRow.querySelector('.line-total');
                
                const qty = parseFloat(qtyInput.value) || 0;
                const cost = parseFloat(costInput.value) || 0;
                const lineTotal = qty * cost;
                
                lineTotalSpan.textContent = '$' + lineTotal.toFixed(2);
                
                // Add animation to total update
                lineTotalSpan.classList.add('animate__animated', 'animate__pulse');
                setTimeout(() => {
                    lineTotalSpan.classList.remove('animate__animated', 'animate__pulse');
                }, 300);
            }
            
            function updateGrandTotal() {
                let grandTotal = 0;
                document.querySelectorAll('.item-row').forEach(itemRow => {
                    const qtyInput = itemRow.querySelector('.qty-input');
                    const costInput = itemRow.querySelector('.cost-price-input');
                    
                    const qty = parseFloat(qtyInput.value) || 0;
                    const cost = parseFloat(costInput.value) || 0;
                    grandTotal += qty * cost;
                });
                
                const grandTotalSpan = document.getElementById('grandTotal');
                grandTotalSpan.textContent = grandTotal.toFixed(2);
                
                // Add animation to grand total update
                grandTotalSpan.classList.add('animate__animated', 'animate__pulse');
                setTimeout(() => {
                    grandTotalSpan.classList.remove('animate__animated', 'animate__pulse');
                }, 300);
            }
            
            function validateForm() {
                const items = document.querySelectorAll('.item-row');
                if (items.length === 0) {
                    showNotification('Please add at least one item.', 'danger');
                    return false;
                }
                
                let hasEmptyFields = false;
                let validationMessage = '';
                let expiredBatches = [];
                
                items.forEach((item, index) => {
                    const batchSelect = item.querySelector('.batch-select');
                    const qtyInput = item.querySelector('.qty-input');
                    const costInput = item.querySelector('.cost-price-input');
                    
                    if (!batchSelect.value || !qtyInput.value || !costInput.value) {
                        hasEmptyFields = true;
                        validationMessage += `Item ${index + 1}: Please fill all fields.\n`;
                    }
                    
                    // Check if batch is expired
                    if (batchSelect.value) {
                        const selectedOption = batchSelect.options[batchSelect.selectedIndex];
                        if (selectedOption.classList.contains('expired')) {
                            expiredBatches.push(index + 1);
                        }
                    }
                });
                
                if (hasEmptyFields) {
                    showNotification('Please fill all fields for each item.', 'danger');
                    return false;
                }
                
                if (expiredBatches.length > 0) {
                    const confirmMessage = `Items ${expiredBatches.join(', ')} use expired batches. Continue anyway?`;
                    if (!confirm(confirmMessage)) {
                        return false;
                    }
                }
                
                showNotification('Form validation successful! You can now submit.', 'success');
                return true;
            }
            
            function showNotification(message, type = 'info') {
                // Remove existing notifications
                const existingNotifications = document.querySelectorAll('.notification-toast');
                existingNotifications.forEach(notification => notification.remove());
                
                // Create notification
                const notification = document.createElement('div');
                notification.className = `notification-toast position-fixed top-0 end-0 m-3 animate__animated animate__fadeInDown`;
                notification.style.zIndex = '9999';
                notification.style.minWidth = '300px';
                
                let icon = '';
                let bgClass = '';
                
                switch(type) {
                    case 'success':
                        icon = 'check-circle';
                        bgClass = 'bg-success text-white';
                        break;
                    case 'danger':
                        icon = 'exclamation-circle';
                        bgClass = 'bg-danger text-white';
                        break;
                    case 'warning':
                        icon = 'exclamation-triangle';
                        bgClass = 'bg-warning text-dark';
                        break;
                    default:
                        icon = 'info-circle';
                        bgClass = 'bg-info text-white';
                }
                
                notification.innerHTML = `
                    <div class="toast show border-0 ${bgClass}" role="alert">
                        <div class="toast-header ${bgClass} border-0">
                            <i class="fas fa-${icon} me-2"></i>
                            <strong class="me-auto">${type.charAt(0).toUpperCase() + type.slice(1)}</strong>
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast"></button>
                        </div>
                        <div class="toast-body">
                            ${message}
                        </div>
                    </div>
                `;
                
                document.body.appendChild(notification);
                
                // Auto-remove after 5 seconds
                setTimeout(() => {
                    notification.classList.add('animate__fadeOutUp');
                    setTimeout(() => {
                        if (notification.parentNode) {
                            notification.remove();
                        }
                    }, 300);
                }, 5000);
            }
            
            // Initialize line totals for existing items
            document.querySelectorAll('.item-row').forEach(itemRow => {
                updateLineTotal(itemRow);
            });
            
            // Auto-hide success message after 5 seconds
            setTimeout(() => {
                const successAlert = document.querySelector('.alert-success-custom');
                if (successAlert) {
                    successAlert.classList.add('animate__fadeOutUp');
                    setTimeout(() => {
                        if (successAlert.parentNode) {
                            successAlert.remove();
                        }
                    }, 500);
                }
            }, 5000);
        });
    </script>
</body>
</html>