<?php
class ContactController {
    public function customers(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();

        $tid = Auth::tenantId();
        $page = (int)($_GET['page'] ?? 1) ?: 1;
        $search = Security::sanitize($_GET['search'] ?? '');

        // Build query with ledger balance
        $sql = "SELECT c.*, COALESCE(SUM(cl.debit - cl.credit), 0) as balance
                FROM customers c
                LEFT JOIN customer_ledger cl ON cl.customer_id = c.id AND cl.tenant_id = c.tenant_id
                WHERE c.tenant_id = ?";

        $params = [$tid];

        if ($search) {
            $sql .= " AND (c.name LIKE ? OR c.phone LIKE ? OR c.email LIKE ?)";
            $params[] = "%{$search}%";
            $params[] = "%{$search}%";
            $params[] = "%{$search}%";
        }

        $sql .= " GROUP BY c.id ORDER BY c.name ASC";

        // Get total count
        $countSql = "SELECT COUNT(*) FROM customers c WHERE c.tenant_id = ?";
        $countParams = [$tid];
        if ($search) {
            $countSql .= " AND (c.name LIKE ? OR c.phone LIKE ? OR c.email LIKE ?)";
            $countParams = array_merge($countParams, ["%{$search}%", "%{$search}%", "%{$search}%"]);
        }
        $countStmt = db()->prepare($countSql);
        $countStmt->execute($countParams);
        $total = (int)$countStmt->fetchColumn();

        // Get paginated data
        $perPage = 15;
        $offset = ($page - 1) * $perPage;
        $sql .= " LIMIT {$perPage} OFFSET {$offset}";
        $stmt = db()->prepare($sql);
        $stmt->execute($params);
        $customers = $stmt->fetchAll();

        $customers = [
            'data' => $customers,
            'total' => $total,
            'last_page' => (int)ceil($total / $perPage),
            'page' => $page
        ];

        $pageTitle = 'Customers';
        ob_start();
        include APP_ROOT . '/views/tenant/contacts/customers.php';
        $content = ob_get_clean();
        include APP_ROOT . '/views/tenant/layouts/main.php';
    }

    public function suppliers(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();

        $tid = Auth::tenantId();
        $page = (int)($_GET['page'] ?? 1) ?: 1;
        $search = Security::sanitize($_GET['search'] ?? '');

        // Build query with ledger balance
        $sql = "SELECT s.*, COALESCE(SUM(sl.debit - sl.credit), 0) as balance
                FROM suppliers s
                LEFT JOIN supplier_ledger sl ON sl.supplier_id = s.id AND sl.tenant_id = s.tenant_id
                WHERE s.tenant_id = ?";

        $params = [$tid];

        if ($search) {
            $sql .= " AND (s.name LIKE ? OR s.phone LIKE ? OR s.email LIKE ?)";
            $params[] = "%{$search}%";
            $params[] = "%{$search}%";
            $params[] = "%{$search}%";
        }

        $sql .= " GROUP BY s.id ORDER BY s.name ASC";

        // Get total count
        $countSql = "SELECT COUNT(*) FROM suppliers s WHERE s.tenant_id = ?";
        $countParams = [$tid];
        if ($search) {
            $countSql .= " AND (s.name LIKE ? OR s.phone LIKE ? OR s.email LIKE ?)";
            $countParams = array_merge($countParams, ["%{$search}%", "%{$search}%", "%{$search}%"]);
        }
        $countStmt = db()->prepare($countSql);
        $countStmt->execute($countParams);
        $total = (int)$countStmt->fetchColumn();

        // Get paginated data
        $perPage = 15;
        $offset = ($page - 1) * $perPage;
        $sql .= " LIMIT {$perPage} OFFSET {$offset}";
        $stmt = db()->prepare($sql);
        $stmt->execute($params);
        $suppliers = $stmt->fetchAll();

        $suppliers = [
            'data' => $suppliers,
            'total' => $total,
            'last_page' => (int)ceil($total / $perPage),
            'page' => $page
        ];

        $pageTitle = 'Suppliers';
        ob_start();
        include APP_ROOT . '/views/tenant/contacts/suppliers.php';
        $content = ob_get_clean();
        include APP_ROOT . '/views/tenant/layouts/main.php';
    }

    public function storeCustomer(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Security::checkCsrf();

        $data = [
            'name'    => Security::sanitize($_POST['name'] ?? ''),
            'email'   => Security::sanitize($_POST['email'] ?? ''),
            'phone'   => Security::sanitize($_POST['phone'] ?? ''),
            'address' => Security::sanitize($_POST['address'] ?? ''),
        ];

        $customerId = Customer::create($data);

        // Return JSON for AJAX requests (from POS)
        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
            header('Content-Type: application/json');
            echo json_encode([
                'success' => true,
                'customer_id' => $customerId,
                'name' => $data['name']
            ]);
            return;
        }

        flash('success', 'Customer added');
        redirectBack();
    }

    public function storeSupplier(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Security::checkCsrf();
        
        $data = [
            'name'    => Security::sanitize($_POST['name'] ?? ''),
            'email'   => Security::sanitize($_POST['email'] ?? ''),
            'phone'   => Security::sanitize($_POST['phone'] ?? ''),
            'address' => Security::sanitize($_POST['address'] ?? ''),
        ];
        
        Supplier::create($data);
        flash('success', 'Supplier added');
        redirectBack();
    }

    public function updateCustomer(int $id): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Security::checkCsrf();

        $data = [
            'name'    => Security::sanitize($_POST['name'] ?? ''),
            'email'   => Security::sanitize($_POST['email'] ?? ''),
            'phone'   => Security::sanitize($_POST['phone'] ?? ''),
            'address' => Security::sanitize($_POST['address'] ?? ''),
        ];

        Customer::update($id, $data);
        flash('success', 'Customer updated');
        redirectBack();
    }

    public function updateSupplier(int $id): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Security::checkCsrf();
        
        $data = [
            'name'    => Security::sanitize($_POST['name'] ?? ''),
            'email'   => Security::sanitize($_POST['email'] ?? ''),
            'phone'   => Security::sanitize($_POST['phone'] ?? ''),
            'address' => Security::sanitize($_POST['address'] ?? ''),
        ];
        
        Supplier::update($id, $data);
        flash('success', 'Supplier updated');
        redirectBack();
    }
}
