<?php
require_once __DIR__ . '/../../classes/Branding.php';
$companyName = Branding::companyName();
$companyLogo = Branding::logoUrl();
$companyLogoFile = Branding::logoFilePath();

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

session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Logger.php';
require_once __DIR__ . '/../../classes/Branch.php';
require_once __DIR__ . '/../../classes/DeliveryNote.php';

$database = new Database();
$conn = $database->getConnection();

$branch = new Branch($conn);
$auth = new Auth($conn);


$logger = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'], $_SESSION['role']);

//$delivery_note = new DeliveryNote($conn, $logger);
$logger = new Logger($conn);
$delivery_note = new DeliveryNote($conn);




if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit();
}

$userRole = $auth->getUserRole($_SESSION['user_id']);
if (!in_array($userRole, ['branch', 'warehouse', 'sales'])) {
    header('Location: ../../unauthorized.php');
    exit();
}

$branchId = $auth->getUserBranch($_SESSION['user_id']);
if (!$branchId) {
    die("Error: You are not assigned to any branch.");
}

$branchDetails = $branch->getBranchById($branchId);
$cashierName = $auth->getUserName($_SESSION['user_id']);
$delivery_note_number = 'DN' . date('Y') . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);

$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_delivery_note'])) {
    $customerName = trim($_POST['customer_name'] ?? '');
    $customerContact = trim($_POST['customer_contact'] ?? '');
    $validityDays = (int)($_POST['validity_days'] ?? 30);
    $notes = trim($_POST['notes'] ?? '');
    $quantity = (int)($_POST['quantity'] ?? 0);
  
    if (empty($customerName) || empty($customerContact) || $quantity <= 0) {
        $message = '<div class="alert alert-danger">Please fill in all required fields.</div>';
    } else {
        $items = [];
        for ($i = 1; $i <= $quantity; $i++) {
            $itemQty = (int)($_POST["item_qty_$i"] ?? 0);
            $itemName = trim($_POST["item_name_$i"] ?? '');
       
           if ($itemQty <= 0 || empty($itemName)) {
                $message = '<div class="alert alert-danger">Please provide valid item details for item ' . $i . '.</div>';
                break;
            }

            $items[] = [
                'qty' => $itemQty,
                'item_name' => $itemName,
             ];
        }

        if (empty($message)) {

            error_log("Items for create_delivery_note: " . print_r($items, true));

				$maxRetries = 3;
                $retryCount = 0;
                do {
                    $delivery_note_number = 'DN' . date('Y') . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);	
                    $result = $delivery_note->createDeliveryNote(
                        $branchId,
                        $_SESSION['user_id'],
                        $delivery_note_number,
                        $customerName,
                        $customerContact,
                        $items,
                        $notes
                    );
                    $retryCount++;
                } while (!$result['success'] && strpos($result['message'], 'Duplicate entry') !== false && $retryCount < $maxRetries);

                if ($result['success']) {
                    $_SESSION['delivery_note_data'] = [
                        'delivery_note_id' => $result['delivery_note_id'],
                        'delivery_note_number' => $delivery_note_number,
                        'customer_name' => $customerName,
                        'customer_contact' => $customerContact,
                        'notes' => $notes,
                        'items' => $items,
                        'created_at' => date('Y-m-d H:i:s'),
                        'created_by_name' => $cashierName,
                        'branch_name' => $companyName,
                        'branch_address' => $branchDetails['branch_address'] ?? '',
                        'branch_phone' => $branchDetails['branch_phone'] ?? '',
                        'branch_email' => $branchDetails['branch_email'] ?? '',
                        'branch_website' => $branchDetails['branch_website'] ?? ''
                    ];
                    header('Location: delivery_note_receipt.php');
                    exit();
                } else {
                    $message = '<div class="alert alert-danger">Failed to create delivery_note: ' . htmlspecialchars($result['message']) . '</div>';
                }
       
        }
    }
}
?>

<?php include __DIR__ . '/../../includes/header.php'; ?>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 900px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .delivery_note-header {
            background: linear-gradient(45deg, #2c3e50, #34495e);
            color: white;
            padding: 30px;
            text-align: center;
            position: relative;
        }

        .company-logo {
            max-height: 100px;
            width: auto;
            margin-bottom: 15px;
        }

        .company-name {
            font-size: 28px;
            font-weight: bold;
            margin-bottom: 10px;
            text-transform: uppercase;
            letter-spacing: 2px;
        }

        .company-tagline {
            font-size: 14px;
            margin-bottom: 20px;
            opacity: 0.9;
            line-height: 1.6;
        }

        .company-details {
            font-size: 12px;
            line-height: 1.8;
            opacity: 0.8;
        }

        .delivery_note-title {
            position: absolute;
            top: 30px;
            right: 30px;
            background: #e74c3c;
            padding: 10px 20px;
            border-radius: 25px;
            font-weight: bold;
            font-size: 18px;
        }

        .delivery_note-number {
            position: absolute;
            top: 80px;
            right: 30px;
            background: rgba(255, 255, 255, 0.2);
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 14px;
        }

        .tpin-number {
            position: absolute;
            top: 120px;
            right: 30px;
            font-size: 12px;
            opacity: 0.8;
        }

        .form-container {
            padding: 40px;
        }

        .form-section {
            margin-bottom: 30px;
            background: #f8f9fa;
            padding: 25px;
            border-radius: 10px;
            border-left: 4px solid #3498db;
        }

        .section-title {
            font-size: 18px;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .section-icon {
            width: 30px;
            height: 30px;
            background: linear-gradient(45deg, #3498db, #2980b9);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 14px;
        }

        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group.full-width {
            grid-column: 1 / -1;
        }

        .form-label {
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .required {
            color: #e74c3c;
        }

        .form-control, .item-input {
            padding: 12px 16px;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s ease;
            background: white;
        }

        .form-control:focus, .item-input:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
            transform: translateY(-1px);
        }

        textarea.form-control {
            resize: vertical;
            min-height: 80px;
        }

        .items-section {
            background: white;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            overflow: hidden;
        }

        .items-header {
            background: linear-gradient(45deg, #34495e, #2c3e50);
            color: white;
            padding: 15px 20px;
            font-weight: 600;
            display: grid;
            grid-template-columns: 80px 1fr 120px 60px;
            gap: 15px;
            align-items: center;
        }

        .item-row {
            padding: 15px 20px;
            border-bottom: 1px solid #e9ecef;
            display: grid;
            grid-template-columns: 80px 1fr 120px 60px;
            gap: 15px;
            align-items: center;
            background: white;
            transition: all 0.2s ease;
        }

        .item-row:hover {
            background: #f8f9fa;
        }

        .item-row:last-child {
            border-bottom: none;
        }

        .item-input {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 13px;
            width: 100%;
        }

        .item-input:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.1);
        }

        .remove-item {
            background: #e74c3c;
            color: white;
            border: none;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
        }

        .remove-item:hover {
            background: #c0392b;
            transform: scale(1.1);
        }

        .totals-section {
            background: #f8f9fa;
            padding: 25px;
            border-radius: 10px;
            margin-top: 20px;
            border: 2px solid #e9ecef;
        }

        .total-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 0;
            font-size: 16px;
        }

        .total-row.grand-total {
            border-top: 2px solid #2c3e50;
            margin-top: 15px;
            padding-top: 15px;
            font-weight: bold;
            font-size: 20px;
            color: #2c3e50;
        }

        .total-amount {
            font-weight: 600;
            color: #27ae60;
        }

        .action-buttons {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 2px solid #e9ecef;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-primary {
            background: linear-gradient(45deg, #3498db, #2980b9);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(52, 152, 219, 0.3);
        }

        .btn-secondary {
            background: #95a5a6;
            color: white;
        }

        .btn-secondary:hover {
            background: #7f8c8d;
            transform: translateY(-2px);
        }

        .btn-success {
            background: linear-gradient(45deg, #27ae60, #229954);
            color: white;
        }

        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(39, 174, 96, 0.3);
        }

        .alert {
            padding: 15px 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .alert-danger {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        @media (max-width: 768px) {
            .container {
                margin: 10px;
                border-radius: 10px;
            }

            .delivery_note-header {
                padding: 20px;
            }

            .delivery_note-title,
            .delivery_note-number,
            .tpin-number {
                position: static;
                margin: 10px 0;
                display: inline-block;
            }

            .form-container {
                padding: 20px;
            }

            .items-header,
            .item-row {
                grid-template-columns: 1fr;
                gap: 10px;
                text-align: center;
            }

            .action-buttons {
                flex-direction: column;
                gap: 15px;
            }
        }

        .container {
            animation: slideUp 0.6s ease-out;
        }

        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .preview-modal {
            max-width: 800px;
            margin: 30px auto;
        }

        .preview-content {
            padding: 20px;
            background: white;
            border-radius: 10px;
        }

        .preview-table {
            width: 100%;
            margin-bottom: 20px;
        }

        .preview-table th {
            background-color: #f5f5f5;
        }
    </style>
    <div class="container">
        <div class="delivery_note-header">
            <div class="delivery_note-title">Delivery Note</div>
            <div class="delivery_note-number">No. <?php echo htmlspecialchars($delivery_note_number); ?></div>
            <div class="tpin-number">TPIN: 30798774</div>

            <div class="company-name"><?php echo htmlspecialchars($companyName); ?></div>
            <div class="company-tagline">
                Dealers in: IT Consumables & Electricals, Desktop Computers, Laptops,<br>
                Projectors, Computer Accessories, Digital Home Theaters, Stereo Headphones,<br>
                Household Furniture's & many more
            </div>
            <div class="company-details">
                <?php echo nl2br(htmlspecialchars($branchDetails['branch_address'] ?? '')); ?><br>
                <?php echo htmlspecialchars($branchDetails['branch_phone'] ?? ''); ?><br>
                Email: <?php echo htmlspecialchars($branchDetails['branch_email'] ?? ''); ?> / Web: <?php echo htmlspecialchars($branchDetails['branch_website'] ?? ''); ?>
            </div>
        </div>

        <div class="form-container">
            <?php if (!empty($message)) echo $message; ?>

            <form method="post" action="" id="delivery_noteForm" class="needs-validation" novalidate>
                <div class="form-section">
                    <div class="section-title">
                        <div class="section-icon">
                            <i class="fas fa-user"></i>
                        </div>
                        Customer Information
                    </div>

                    <div class="form-grid">
                        <div class="form-group full-width">
                            <label for="customer_name" class="form-label">
                                <i class="fas fa-building"></i>
                                Customer/Company Name: <span class="required">*</span>
                            </label>
                            <input type="text" class="form-control" id="customer_name" name="customer_name"
                                   placeholder="Customer/Company Name" required>
                        </div>

                        <div class="form-group full-width">
                            <label for="customer_contact" class="form-label">
                                <i class="fas fa-address-book"></i>
                                Contact Details: <span class="required">*</span>
                            </label>
                            <textarea class="form-control" id="customer_contact" name="customer_contact"
                                      placeholder="Address, Phone, Email" required></textarea>
                        </div>

                        <div class="form-group">
                            <label for="validity_days" class="form-label">
                                <i class="fas fa-calendar"></i>
                                Valid for (days): <span class="required">*</span>
                            </label>
                            <input type="number" class="form-control" id="validity_days" name="validity_days"
                                   value="30" min="1" max="365" required>
                        </div>
                    </div>
                </div>

                <div class="form-section">
                    <div class="section-title">
                        <div class="section-icon">
                            <i class="fas fa-list"></i>
                        </div>
                        Delivery Note Items
                        <button type="button" class="btn btn-success" onclick="addItem()" style="margin-left: auto;">
                            <i class="fas fa-plus"></i> Add Item
                        </button>
                    </div>

                    <div class="items-section">
                        <div class="items-header">
                            <div>Qty</div>
                            <div>Item Name</div>
                            <div></div>
                        </div>

                        <div id="items-container"></div>
                    </div>
                </div>

          
                <div class="form-section">
                    <div class="section-title">
                        <div class="section-icon">
                            <i class="fas fa-sticky-note"></i>
                        </div>
                        Additional Notes
                    </div>

                    <div class="form-group">
                        <textarea class="form-control" id="notes" name="notes" rows="3"
                                  placeholder="Any additional notes or terms..."></textarea>
                    </div>
                </div>

                <input type="hidden" name="quantity" id="quantity" value="0">
                <input type="hidden" name="create_delivery_note" value="1">

                <div class="action-buttons">
                    <a href="list_delivery_notes.php?branch_id=<?php echo $branchId; ?>" class="btn btn-secondary">
                        <i class="fas fa-times"></i>
                        Cancel
                    </a>

                    <div style="display: flex; gap: 15px;">
                        <button type="button" class="btn btn-primary" onclick="previewdelivery_note()">
                            <i class="fas fa-eye"></i>
                            Preview
                        </button>
                        <button type="submit" class="btn btn-success">
                            <i class="fas fa-file-alt"></i>
                            Create Delivery Note
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>


    <div class="modal fade" id="previewModal" tabindex="-1" role="dialog" aria-labelledby="previewModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl preview-modal" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="previewModalLabel">delivery_note Preview</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body preview-content">
                    <div class="text-center">
                        <img src="<?php echo htmlspecialchars($companyLogo); ?>" alt="<?php echo htmlspecialchars($companyName); ?> Logo" style="max-height: 100px; width: auto; margin-bottom: 15px;">
                        <h2>delivery_note</h2>
                        <h4><?php echo htmlspecialchars($companyName); ?></h4>
                        <p><?php echo nl2br(htmlspecialchars($branchDetails['branch_address'] ?? '')); ?></p>
                        <p><?php echo htmlspecialchars($branchDetails['branch_phone'] ?? ''); ?></p>
                    </div>
                    <div class="receipt-info mt-4">
                        <div class="row">
                            <div class="col-md-6">
                                <p><strong>delivery_note #:</strong> <?php echo htmlspecialchars($delivery_note_number); ?></p>
                                <p><strong>Date:</strong> <?php echo date('Y-m-d'); ?></p>
                                <p><strong>Prepared By:</strong> <?php echo htmlspecialchars($cashierName); ?></p>
                            </div>
                            <div class="col-md-6">
                                <p><strong>Customer:</strong> <span id="preview-customer-name"></span></p>
                                <p><strong>Contact:</strong> <span id="preview-customer-contact"></span></p>
                                <p><strong>Valid Until:</strong> <span id="preview-valid-until"></span></p>
                            </div>
                        </div>
                    </div>
                    <table class="table table-bordered preview-table mt-4">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Item Name</th>
                                <th>Quantity</th>
                            </tr>
                        </thead>
                        <tbody id="preview-items"></tbody>
                      
                    </table>
                    <div class="receipt-notes">
                        <h5>Notes:</h5>
                        <p id="preview-notes">No additional notes provided.</p>
                    </div>
                   
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        let itemCounter = 0;

        function addItem() {
            itemCounter++;
            const container = document.getElementById('items-container');
            const itemRow = document.createElement('div');
            itemRow.className = 'item-row';
            itemRow.id = `item-${itemCounter}`;

            itemRow.innerHTML = `
                <input type="number" class="item-input" name="item_qty_${itemCounter}"
                       placeholder="Enter quantity" min="1" onchange="calculateTotal(${itemCounter})" required>
                <input type="text" class="item-input" name="item_name_${itemCounter}"
                       placeholder="Enter item name" onchange="calculateTotal(${itemCounter})" required>
               
                <button type="button" class="remove-item" onclick="removeItem(${itemCounter})">
                    <i class="fas fa-times"></i>
                </button>
            `;

            container.appendChild(itemRow);
            updateQuantity();
           
        }

        function removeItem(id) {
            const item = document.getElementById(`item-${id}`);
            if (item) {
                item.remove();
                updateQuantity();
         }
        }

        function calculateTotal(id) {
            const qtyInput = document.querySelector(`input[name="item_qty_${id}"]`);
            const qty = parseFloat(qtyInput.value) || 0;
            if (qty < 1) {
                qtyInput.value = 1;
            }
           
        }

      function updateQuantity() {
            const itemRows = document.querySelectorAll('.item-row').length;
            document.getElementById('quantity').value = itemRows;
        }

        function previewdelivery_note() {
            const customerName = document.getElementById('customer_name').value || 'Not provided';
            const customerContact = document.getElementById('customer_contact').value || 'Not provided';
            const validityDays = parseInt(document.getElementById('validity_days').value) || 30;
            const notes = document.getElementById('notes').value || 'No additional notes provided.';

            if (!customerName || !customerContact || document.querySelectorAll('.item-row').length === 0) {
                alert('Please fill in customer information and add at least one item.');
                return;
            }


            let hasDefaultQty = false;
            document.querySelectorAll('.item-row').forEach(row => {
                const qty = parseFloat(row.querySelector(`input[name^="item_qty_"]`).value) || 0;
                if (qty === 1) {
                    hasDefaultQty = true;
                }
            });
            if (hasDefaultQty) {
                if (!confirm('Some items have a quantity of 1. Are you sure these quantities are correct?')) {
                    return;
                }
            }

            const validUntil = new Date();
            validUntil.setDate(validUntil.getDate() + validityDays);
            const formattedValidUntil = validUntil.toISOString().split('T')[0];

            document.getElementById('preview-customer-name').textContent = customerName;
            document.getElementById('preview-customer-contact').textContent = customerContact;
            document.getElementById('preview-valid-until').textContent = formattedValidUntil;
            document.getElementById('preview-valid-until-footer').textContent = formattedValidUntil;
            document.getElementById('preview-notes').textContent = notes;

            const itemsContainer = document.getElementById('preview-items');
            itemsContainer.innerHTML = '';
            let subtotal = 0;

            document.querySelectorAll('.item-row').forEach((row, index) => {
                const qtyInput = row.querySelector(`input[name^="item_qty_"]`);
                const qty = parseFloat(qtyInput.value) || 0;
                if (qty < 1) {
                    qtyInput.value = 1;
                }
                const itemName = row.querySelector(`input[name^="item_name_"]`).value || 'Unknown Item';
               

                itemsContainer.innerHTML += `
                    <tr>
                        <td>${index + 1}</td>
                        <td>${itemName}</td>
                        <td>${qty}</td>
                    </tr>
                `;
            });

            bootstrap.Modal.getOrCreateInstance(document.getElementById('previewModal')).show();
        }

        document.addEventListener('DOMContentLoaded', function() {
            addItem();

            const form = document.getElementById('delivery_noteForm');
            form.addEventListener('submit', function(event) {
                if (form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                }

                let hasDefaultQty = false;
                document.querySelectorAll('input[name^="item_qty_"]').forEach(input => {
                    const qty = parseFloat(input.value) || 0;
                    if (qty < 1) {
                        input.value = 1;
                    }
                    if (qty === 1) {
                        hasDefaultQty = true;
                    }
                });
                if (hasDefaultQty) {
                    if (!confirm('Some items have a quantity of 1. Are you sure these quantities are correct?')) {
                        event.preventDefault();
                        event.stopPropagation();
                        return;
                    }
                }
                calculateGrandTotal();
                form.classList.add('was-validated');
            });
        });
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>