<?php
declare(strict_types=1);

require_once __DIR__ . '/../../app/Config/database.php';

class Customer
{
    private PDO $db;

    public function __construct()
    {
        $this->db = Database::getConnection();
    }

    /**
     * Get all customers.
     */
    public function getAll(): array
    {
        $sql = "SELECT * FROM customers ORDER BY name ASC";
        return $this->db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * Get a single customer by ID.
     */
    public function getById(int $id): ?array
    {
        $stmt = $this->db->prepare("SELECT * FROM customers WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    }

    /**
     * Create (Add) a new customer.
     */
    public function create(array $data): bool
    {
        try {
            $stmt = $this->db->prepare("
                INSERT INTO customers (name, email, contact, status)
                VALUES (?, ?, ?, ?)
            ");
            return $stmt->execute([
                $data['name'] ?? '',
                $data['email'] ?? null,
                $data['contact'] ?? null,
                $data['status'] ?? 'active'
            ]);
        } catch (PDOException $e) {
            error_log('Customer::create error → ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Update existing customer.
     */
    public function update(int $id, array $data): bool
    {
        try {
            $stmt = $this->db->prepare("
                UPDATE customers
                SET name = ?, email = ?, contact = ?, status = ?, updated_at = NOW()
                WHERE id = ?
            ");
            return $stmt->execute([
                $data['name'] ?? '',
                $data['email'] ?? null,
                $data['contact'] ?? null,
                $data['status'] ?? 'active',
                $id
            ]);
        } catch (PDOException $e) {
            error_log('Customer::update error → ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Delete a customer by ID.
     */
    public function delete(int $id): bool
    {
        try {
            $stmt = $this->db->prepare("DELETE FROM customers WHERE id = ?");
            return $stmt->execute([$id]);
        } catch (PDOException $e) {
            error_log('Customer::delete error → ' . $e->getMessage());
            return false;
        }
    }
}
