<?php

require_once 'Logger.php';
require_once 'Notifications.php';

class LoanLaybuy {
    private $conn;
    private $logger;
    private $notifications;
    private $table_name = "loans_laybuys";

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

    public function createLoanLaybuy($branch_id, $user_id, $record_number, $item_name, $customer_name, $customer_contact, $amount, $status, $validity_days, $notes) {
        try {
            $query = "INSERT INTO " . $this->table_name . "
                      (branch_id, user_id, record_number, item_name, customer_name, customer_contact, method, amount, status, valid_until, notes, created_at)
                      VALUES (:branch_id, :user_id, :record_number, :item_name, :customer_name, :customer_contact, 'laybuy', :amount, :status, :valid_until, :notes, NOW())";
            $stmt = $this->conn->prepare($query);

            $valid_until = date('Y-m-d H:i:s', strtotime("+$validity_days days"));

            $stmt->bindParam(':branch_id', $branch_id, PDO::PARAM_INT);
            $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
            $stmt->bindParam(':record_number', $record_number);
            $stmt->bindParam(':item_name', $item_name);
            $stmt->bindParam(':customer_name', $customer_name);
            $stmt->bindParam(':customer_contact', $customer_contact);
            $stmt->bindParam(':amount', $amount);
            $stmt->bindParam(':status', $status);
            $stmt->bindParam(':valid_until', $valid_until);
            $stmt->bindParam(':notes', $notes);

            if ($stmt->execute()) {
                $recordId = $this->conn->lastInsertId();

                if ($this->logger) {
                    $recordData = [
                        'branch_id' => $branch_id,
                        'user_id' => $user_id,
                        'record_number' => $record_number,
                        'item_name' => $item_name,
                        'customer_name' => $customer_name,
                        'customer_contact' => $customer_contact,
                        'amount' => $amount,
                        'status' => $status,
                        'valid_until' => $valid_until,
                        'notes' => $notes
                    ];
                    $this->logger->logLoanLaybuy('CREATE', $recordId, $recordData);
                }

                $message = "Laybuy record ".$record_number." has been created for branch ".$branch_id.".";
                $this->notifications->createNotification($branch_id, $message, 'Admin');

                return ['success' => true, 'record_id' => $recordId];
            }
            return ['success' => false, 'message' => 'Failed to create record.'];
        } catch (PDOException $e) {
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }

    public function getLoansLaybuysByBranch($branch_id) {
        $query = "SELECT * FROM " . $this->table_name . " WHERE branch_id = :branch_id ORDER BY created_at DESC";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':branch_id', $branch_id, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function getLoanLaybuyById($record_id) {
        try {
            $query = "SELECT * FROM " . $this->table_name . " WHERE record_id = :record_id";
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':record_id', $record_id, PDO::PARAM_INT);
            $stmt->execute();
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            return $result ?: null;
        } catch (PDOException $e) {
            error_log("Error fetching loan/laybuy by ID: " . $e->getMessage());
            return null;
        }
    }

    public function updateLoanLaybuy($record_id, $customer_name, $customer_contact, $valid_until, $status, $item_name, $amount, $notes) {
        try {
            $oldData = null;
            if ($this->logger) {
                $oldRecord = $this->getLoanLaybuyById($record_id);
                if ($oldRecord) {
                    $oldData = [
                        'customer_name' => $oldRecord['customer_name'],
                        'customer_contact' => $oldRecord['customer_contact'],
                        'valid_until' => $oldRecord['valid_until'],
                        'status' => $oldRecord['status'],
                        'item_name' => $oldRecord['item_name'],
                        'amount' => $oldRecord['amount'],
                        'notes' => $oldRecord['notes']
                    ];
                }
            }

            $query = "UPDATE " . $this->table_name . "
                      SET customer_name = :customer_name,
                          customer_contact = :customer_contact,
                          valid_until = :valid_until,
                          status = :status,
                          item_name = :item_name,
                          amount = :amount,
                          notes = :notes
                      WHERE record_id = :record_id";
            $stmt = $this->conn->prepare($query);

            $stmt->bindParam(':customer_name', $customer_name);
            $stmt->bindParam(':customer_contact', $customer_contact);
            $stmt->bindParam(':valid_until', $valid_until);
            $stmt->bindParam(':status', $status);
            $stmt->bindParam(':item_name', $item_name);
            $stmt->bindParam(':amount', $amount);
            $stmt->bindParam(':notes', $notes);
            $stmt->bindParam(':record_id', $record_id, PDO::PARAM_INT);

            $result = $stmt->execute();

            if ($result && $this->logger && $oldData) {
                $newData = [
                    'customer_name' => $customer_name,
                    'customer_contact' => $customer_contact,
                    'valid_until' => $valid_until,
                    'status' => $status,
                    'item_name' => $item_name,
                    'amount' => $amount,
                    'notes' => $notes
                ];
                $this->logger->logLoanLaybuy('UPDATE', $record_id, $newData, $oldData);
            }

            return $result;
        } catch (PDOException $e) {
            error_log("Error updating loan/laybuy: " . $e->getMessage());
            return false;
        }
    }
	
	public function getPaymentDetails() {
       

/*	   $query = "SELECT * FROM users";
        $stmt = $this->db->prepare($query);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC); */
    }




    public function deleteLoanLaybuy($record_id) {
        try {
            $recordData = null;
            if ($this->logger) {
                $recordData = $this->getLoanLaybuyById($record_id);
            }

            $query = "DELETE FROM " . $this->table_name . " WHERE record_id = :record_id";
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':record_id', $record_id, PDO::PARAM_INT);
            $result = $stmt->execute();

            if ($result && $this->logger && $recordData) {
                $this->logger->logLoanLaybuy('DELETE', $record_id, null, $recordData);
            }

            return $result;
        } catch (PDOException $e) {
            error_log("Error deleting loan/laybuy: " . $e->getMessage());
            return false;
        }
    }
}
?>
