<?php
require_once __DIR__ . '/../config/Database.php';

class Supplier {
    private $db;
    private $conn;
    
    public function __construct() {
        $this->db = new Database();
        $this->conn = $this->db->getConnection();
    }
    
    public function getAllSuppliers() {
        $query = "SELECT * FROM suppliers WHERE status = 'active' ORDER BY name";
        $result = $this->conn->query($query);
        return $result->fetch_all(MYSQLI_ASSOC);
    }
    
    public function getSupplier($supplierId) {
        $query = "SELECT * FROM suppliers WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        $stmt->bind_param("i", $supplierId);
        $stmt->execute();
        return $stmt->get_result()->fetch_assoc();
    }
    
    public function createSupplier($data) {
        $query = "INSERT INTO suppliers (name, contact_person, phone, email, address, city, postal_code) 
                  VALUES (?, ?, ?, ?, ?, ?, ?)";
        $stmt = $this->conn->prepare($query);
        $stmt->bind_param("sssssss", $data['name'], $data['contact_person'], $data['phone'], 
                          $data['email'], $data['address'], $data['city'], $data['postal_code']);
        if ($stmt->execute()) {
            return ['success' => true, 'id' => $this->conn->insert_id];
        }
        return ['success' => false];
    }
    
    public function createPayment($data) {
        $query = "INSERT INTO supplier_payments (id, supplier_id, total_bill, paid_amount, due_amount, 
                  payment_date, payment_method, reference, invoice_ref, notes) 
                  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        $stmt = $this->conn->prepare($query);
        $stmt->bind_param("sidddsssss", $data['id'], $data['supplier_id'], $data['total_bill'], 
                          $data['paid_amount'], $data['due_amount'], $data['payment_date'], 
                          $data['payment_method'], $data['reference'], $data['invoice_ref'], $data['notes']);
        
        return $stmt->execute();
    }
    
    public function getSupplierPayments($supplierId) {
        $query = "SELECT * FROM supplier_payments WHERE supplier_id = ? ORDER BY payment_date DESC";
        $stmt = $this->conn->prepare($query);
        $stmt->bind_param("i", $supplierId);
        $stmt->execute();
        return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    }
    
    public function getSupplierBalance($supplierId) {
        $query = "SELECT 
                    SUM(total_bill) as total_bill,
                    SUM(paid_amount) as paid_amount,
                    SUM(due_amount) as due_amount
                  FROM supplier_payments 
                  WHERE supplier_id = ?";
        
        $stmt = $this->conn->prepare($query);
        $stmt->bind_param("i", $supplierId);
        $stmt->execute();
        return $stmt->get_result()->fetch_assoc();
    }
}
?>
