<?php

require_once 'Logger.php';

class DeliveryNote {
    private $conn;
    private $logger;

    public function __construct($conn, $logger = null) {
        $this->conn = $conn;
        $this->logger = $logger;
    }

    /**
     * CREATE DELIVERY NOTE
     */
    public function createDeliveryNote($branchId, $createdBy, $noteNumber, $customerName, $customerContact, $items, $notes = '')
    {
        try {
            if (empty($noteNumber) || empty($customerName) || empty($items)) {
                throw new Exception("Missing required delivery note data.");
            }

            if (!is_array($items) || count($items) === 0) {
                throw new Exception("Items must be a valid array.");
            }

            $this->conn->beginTransaction();

            // Insert header
            $sql = "INSERT INTO delivery_notes 
                    (delivery_note_number, branch_id, created_by, customer_name, customer_contact, notes, created_at)
                    VALUES (:number, :branch, :user, :customer_name, :customer_contact, :notes, NOW())";

            $stmt = $this->conn->prepare($sql);
            $stmt->execute([
                ':number' => $noteNumber,
                ':branch' => $branchId,
                ':user' => $createdBy,
                ':customer_name' => $customerName,
                ':customer_contact' => $customerContact,
                ':notes' => $notes
            ]);

            $deliveryNoteId = $this->conn->lastInsertId();

            // Insert items
            $itemSql = "INSERT INTO delivery_note_items 
                        (delivery_note_id, item_name, quantity)
                        VALUES (:id, :name, :qty)";
            $itemStmt = $this->conn->prepare($itemSql);

            foreach ($items as $item) {
                if (!isset($item['item_name']) || !isset($item['qty'])) {
                    throw new Exception("Invalid item structure.");
                }

                if ($item['qty'] <= 0 || empty($item['item_name'])) {
                    throw new Exception("Invalid item values.");
                }

                $itemStmt->execute([
                    ':id' => $deliveryNoteId,
                    ':name' => $item['item_name'],
                    ':qty' => $item['qty']
                ]);
            }

            $this->conn->commit();

            // Logging
            if ($this->logger) {
                $this->logger->log('CREATE_DELIVERY_NOTE', [
                    'delivery_note_id' => $deliveryNoteId,
                    'note_number' => $noteNumber,
                    'customer_name' => $customerName,
                    'items_count' => count($items)
                ]);
            }

            return [
                'success' => true,
                'delivery_note_id' => $deliveryNoteId,
                'message' => 'Delivery note created successfully.'
            ];

        } catch (Exception $e) {
            if ($this->conn->inTransaction()) {
                $this->conn->rollBack();
            }

            error_log("Delivery Note Error: " . $e->getMessage());

            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    /**
     * GET DELIVERY NOTE BY ID
     */
    public function getDeliveryNoteById($deliveryNoteId)
    {
        $sql = "SELECT * FROM delivery_notes WHERE delivery_note_id = :id";
        $stmt = $this->conn->prepare($sql);
        $stmt->execute([':id' => $deliveryNoteId]);

        $note = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($note) {
            $itemSql = "SELECT item_name, quantity 
                        FROM delivery_note_items 
                        WHERE delivery_note_id = :id";
            $itemStmt = $this->conn->prepare($itemSql);
            $itemStmt->execute([':id' => $deliveryNoteId]);

            $note['items'] = $itemStmt->fetchAll(PDO::FETCH_ASSOC);
        }

        return $note ?: [];
    }

    /**
     * GET ALL DELIVERY NOTES
     */
    public function getAllDeliveryNotes()
    {
        $sql = "SELECT * FROM delivery_notes ORDER BY created_at DESC";
        $stmt = $this->conn->prepare($sql);
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * DELETE DELIVERY NOTE
     */
    public function deleteDeliveryNote($deliveryNoteId)
    {
        try {
            $this->conn->beginTransaction();

            // Delete items first
            $stmt1 = $this->conn->prepare("DELETE FROM delivery_note_items WHERE delivery_note_id = :id");
            $stmt1->execute([':id' => $deliveryNoteId]);

            // Delete header
            $stmt2 = $this->conn->prepare("DELETE FROM delivery_notes WHERE delivery_note_id = :id");
            $success = $stmt2->execute([':id' => $deliveryNoteId]);

            $this->conn->commit();

            if ($this->logger && $success) {
                $this->logger->log('DELETE_DELIVERY_NOTE', [
                    'delivery_note_id' => $deliveryNoteId
                ]);
            }

            return $success;

        } catch (Exception $e) {
            $this->conn->rollBack();
            error_log("Delete Delivery Note Error: " . $e->getMessage());
            return false;
        }
    }
	
	/**
 * GET DELIVERY NOTES BY BRANCH
 */
public function getDeliveryNotesByBranch($branchId)
{
    try {
        if (empty($branchId)) {
            throw new Exception("Branch ID is required.");
        }

        // Get delivery notes for branch
        $sql = "SELECT * 
                FROM delivery_notes 
                WHERE branch_id = :branch_id 
                ORDER BY created_at DESC";

        $stmt = $this->conn->prepare($sql);
        $stmt->execute([':branch_id' => $branchId]);

        $notes = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Attach items to each note
        $itemSql = "SELECT item_name, quantity 
                    FROM delivery_note_items 
                    WHERE delivery_note_id = :id";

        $itemStmt = $this->conn->prepare($itemSql);

        foreach ($notes as &$note) {
            $itemStmt->execute([':id' => $note['delivery_note_id']]);
            $note['items'] = $itemStmt->fetchAll(PDO::FETCH_ASSOC);
        }

        return $notes;

    } catch (Exception $e) {
        error_log("Get Delivery Notes By Branch Error: " . $e->getMessage());
        return [];
    }
}
	
	
	
}
?>