<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Purchase_entry_model extends CI_Model {

    protected $table        = 'purchase_entry_master';
    protected $table_items  = 'purchase_entry_items';

    // ── LIST ─────────────────────────────────────────────────────────────────
    public function getAll() {
        $this->db->select('pem.*, s.supplier_name');
        $this->db->from('purchase_entry_master pem');
        $this->db->join('supplier_master s', 's.id = pem.supplier_id', 'left');
        $this->db->order_by('pem.purchase_date', 'DESC');
        return $this->db->get()->result();
    }

    // ── ONE HEADER ───────────────────────────────────────────────────────────
    public function getOne($id) {
        $this->db->select('pem.*, s.supplier_name');
        $this->db->from('purchase_entry_master pem');
        $this->db->join('supplier_master s', 's.id = pem.supplier_id', 'left');
        $this->db->where('pem.id', $id);
        return $this->db->get()->row();
    }

    // ── ITEMS FOR A PURCHASE ─────────────────────────────────────────────────
    public function getItems($purchase_id) {
        $this->db->select('pei.*, p.product_name, u.unit_name');
        $this->db->from('purchase_entry_items pei');
        $this->db->join('product_master p',  'p.id = pei.product_id', 'left');
        $this->db->join('unit_master u',     'u.id = p.unit_id',      'left');
        $this->db->where('pei.purchase_id', $purchase_id);
        return $this->db->get()->result();
    }

    // ── INSERT HEADER + ITEMS ────────────────────────────────────────────────
    public function insertWithItems($header, $items) {
        $this->db->trans_start();

        $this->db->insert($this->table, $header);
        $purchase_id = $this->db->insert_id();

        foreach ($items as $item) {
            $item['purchase_id'] = $purchase_id;
            // Update product stock
            $this->db->query(
                "UPDATE product_master SET current_stock = current_stock + ? WHERE id = ?",
                [(int)$item['qty'], (int)$item['product_id']]
            );
            $this->db->insert($this->table_items, $item);
        }

        $this->db->trans_complete();
        return $this->db->trans_status() ? $purchase_id : false;
    }

    // ── UPDATE HEADER + ITEMS ────────────────────────────────────────────────
    public function updateWithItems($id, $header, $items) {
        $this->db->trans_start();

        // Reverse old stock
        $old_items = $this->getItems($id);
        foreach ($old_items as $oi) {
            $this->db->query(
                "UPDATE product_master SET current_stock = current_stock - ? WHERE id = ?",
                [(int)$oi->qty, (int)$oi->product_id]
            );
        }

        $this->db->update($this->table, $header, ['id' => $id]);
        $this->db->delete($this->table_items, ['purchase_id' => $id]);

        foreach ($items as $item) {
            $item['purchase_id'] = $id;
            $this->db->query(
                "UPDATE product_master SET current_stock = current_stock + ? WHERE id = ?",
                [(int)$item['qty'], (int)$item['product_id']]
            );
            $this->db->insert($this->table_items, $item);
        }

        $this->db->trans_complete();
        return $this->db->trans_status();
    }

    // ── DELETE ───────────────────────────────────────────────────────────────
    

    // ── DELETE ───────────────────────────────────────────────────────
    public function delete($id) {
        $this->db->trans_start();

        $items = $this->getItems($id);

        foreach ($items as $item) {
            $this->db->query(
                "UPDATE product_master SET current_stock = current_stock - ? WHERE id = ?",
                [(int)$item->qty, (int)$item->product_id]
            );
        }

        $this->db->delete($this->table, ['id' => $id]);

        $this->db->trans_complete();

        return $this->db->trans_status();
    }

    // ── TOTAL PURCHASE AMOUNT ─────────────────────────────────────────
    public function getTotalAmount()
    {
        $this->db->select_sum('grand_total');
        $query = $this->db->get($this->table);

        return $query->row()->grand_total ?? 0;
    }

}