<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'Inventory Suppliers';

if (!function_exists('h')) {
    function h($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('money_fmt')) {
    function money_fmt($amount): string { return number_format((float)$amount, 2); }
}
if (!function_exists('sup_flash')) {
    function sup_flash(string $type, string $message): void {
        $_SESSION['suppliers_flash'][] = ['type' => $type, 'message' => $message];
    }
}
if (!function_exists('sup_get_flash')) {
    function sup_get_flash(): array {
        $items = $_SESSION['suppliers_flash'] ?? [];
        unset($_SESSION['suppliers_flash']);
        return $items;
    }
}
if (!function_exists('sup_bool')) {
    function sup_bool($value): int {
        return in_array((string)$value, ['1','yes','true','on'], true) ? 1 : 0;
    }
}
if (!function_exists('sup_column_exists')) {
    function sup_column_exists(PDO $pdo, string $tableName, string $columnName): bool {
        $stmt = $pdo->prepare("
            SELECT COUNT(*)
            FROM information_schema.columns
            WHERE table_schema = DATABASE()
              AND table_name = :table_name
              AND column_name = :column_name
        ");
        $stmt->execute([':table_name' => $tableName, ':column_name' => $columnName]);
        return (int)$stmt->fetchColumn() > 0;
    }
}

if (!function_exists('sup_payment_term_by_id')) {
    function sup_payment_term_by_id(PDO $pdo, int $termId): ?array {
        if ($termId <= 0) {
            return null;
        }
        $stmt = $pdo->prepare("SELECT * FROM supplier_payment_terms WHERE id = :id AND is_active = 1 LIMIT 1");
        $stmt->execute([':id' => $termId]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        return $row ?: null;
    }
}
if (!function_exists('sup_payment_term_by_text')) {
    function sup_payment_term_by_text(PDO $pdo, string $value): ?array {
        $value = trim($value);
        if ($value === '') {
            return null;
        }
        $stmt = $pdo->prepare("
            SELECT *
            FROM supplier_payment_terms
            WHERE is_active = 1
              AND (LOWER(term_code) = LOWER(:value) OR LOWER(term_name) = LOWER(:value))
            LIMIT 1
        ");
        $stmt->execute([':value' => $value]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        return $row ?: null;
    }
}

if (!function_exists('sup_clean_header')) {
    function sup_clean_header($value): string {
        return strtolower(preg_replace('/[^a-z0-9]+/', '', trim((string)$value)));
    }
}
if (!function_exists('sup_excel_col_to_index')) {
    function sup_excel_col_to_index(string $letters): int {
        $letters = strtoupper($letters);
        $num = 0;
        for ($i = 0; $i < strlen($letters); $i++) {
            $num = ($num * 26) + (ord($letters[$i]) - 64);
        }
        return $num - 1;
    }
}
if (!function_exists('sup_read_csv_rows')) {
    function sup_read_csv_rows(string $tmpPath): array {
        $rows = [];
        $handle = fopen($tmpPath, 'rb');
        if (!$handle) {
            throw new RuntimeException('Could not open uploaded CSV file.');
        }

        $first = fgets($handle);
        if ($first === false) {
            fclose($handle);
            return [];
        }

        $first = preg_replace('/^\xEF\xBB\xBF/', '', $first);
        rewind($handle);

        while (($row = fgetcsv($handle, 0, ',')) !== false) {
            $rows[] = array_map(static fn($v) => trim((string)$v), $row);
        }

        fclose($handle);
        return $rows;
    }
}
if (!function_exists('sup_read_xlsx_rows')) {
    function sup_read_xlsx_rows(string $tmpPath): array {
        if (!class_exists('ZipArchive')) {
            throw new RuntimeException('XLSX import requires PHP ZipArchive. Please enable ZipArchive or upload CSV.');
        }

        $zip = new ZipArchive();
        if ($zip->open($tmpPath) !== true) {
            throw new RuntimeException('Could not open uploaded Excel file.');
        }

        $shared = [];
        $sharedXml = $zip->getFromName('xl/sharedStrings.xml');
        if ($sharedXml !== false) {
            $xml = simplexml_load_string($sharedXml);
            if ($xml) {
                foreach ($xml->si as $si) {
                    $text = '';
                    if (isset($si->t)) {
                        $text = (string)$si->t;
                    } elseif (isset($si->r)) {
                        foreach ($si->r as $r) {
                            $text .= (string)$r->t;
                        }
                    }
                    $shared[] = $text;
                }
            }
        }

        $sheetPath = 'xl/worksheets/sheet1.xml';
        $sheetXml = $zip->getFromName($sheetPath);
        if ($sheetXml === false) {
            $zip->close();
            throw new RuntimeException('Could not find the first worksheet in the Excel file.');
        }

        $xml = simplexml_load_string($sheetXml);
        if (!$xml) {
            $zip->close();
            throw new RuntimeException('Could not read the worksheet data.');
        }

        $rows = [];
        foreach ($xml->sheetData->row as $rowNode) {
            $row = [];
            foreach ($rowNode->c as $cell) {
                $ref = (string)$cell['r'];
                preg_match('/^([A-Z]+)/i', $ref, $m);
                $idx = isset($m[1]) ? sup_excel_col_to_index($m[1]) : count($row);

                $type = (string)$cell['t'];
                $value = '';
                if ($type === 's') {
                    $si = (int)$cell->v;
                    $value = $shared[$si] ?? '';
                } elseif ($type === 'inlineStr') {
                    $value = isset($cell->is->t) ? (string)$cell->is->t : '';
                } else {
                    $value = isset($cell->v) ? (string)$cell->v : '';
                }
                $row[$idx] = trim($value);
            }

            if ($row) {
                ksort($row);
                $max = max(array_keys($row));
                $full = [];
                for ($i = 0; $i <= $max; $i++) {
                    $full[] = $row[$i] ?? '';
                }
                $rows[] = $full;
            }
        }

        $zip->close();
        return $rows;
    }
}
if (!function_exists('sup_read_import_rows')) {
    function sup_read_import_rows(array $file): array {
        if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
            throw new RuntimeException('Please choose a valid CSV or Excel file to import.');
        }

        $name = strtolower((string)($file['name'] ?? ''));
        $ext = pathinfo($name, PATHINFO_EXTENSION);

        if ($ext === 'csv' || $ext === 'txt') {
            return sup_read_csv_rows((string)$file['tmp_name']);
        }

        if ($ext === 'xlsx') {
            return sup_read_xlsx_rows((string)$file['tmp_name']);
        }

        throw new RuntimeException('Unsupported file type. Please upload CSV or XLSX.');
    }
}
if (!function_exists('sup_get_cell')) {
    function sup_get_cell(array $mapped, array $aliases, string $field): string {
        foreach ($aliases[$field] ?? [] as $alias) {
            $key = sup_clean_header($alias);
            if (array_key_exists($key, $mapped)) {
                return trim((string)$mapped[$key]);
            }
        }
        return '';
    }
}

if (!function_exists('sup_import_aliases')) {
    function sup_import_aliases(): array {
        return [
            'supplier_code'  => ['supplier_code','supplier code','code','suppliercode','vendor code','vendor_code','account code','account_code'],
            'supplier_name'  => ['supplier_name','supplier name','supplier','name','vendor','vendor name','vendor_name','company','company name','company_name'],
            'contact_person' => ['contact_person','contact person','contact','contact name','contact_name','person'],
            'phone'          => ['phone','telephone','tel','mobile','cell','cellphone','contact number','contact_number'],
            'email'          => ['email','e-mail','mail','email address','email_address'],
            'address'        => ['address','physical address','physical_address','street','postal address','postal_address'],
            'payment_terms'  => ['payment_terms','payment terms','terms','credit terms','credit_terms'],
            'tax_number'     => ['tax_number','tax number','tax no','tax_no','vat','vat number','vat_number','tin','tin number'],
            'notes'          => ['notes','note','comments','comment','remarks','remark'],
            'is_active'      => ['is_active','active','status','enabled']
        ];
    }
}
if (!function_exists('sup_normalize_import_bool')) {
    function sup_normalize_import_bool(string $value): int {
        $v = strtolower(trim($value));
        if ($v === '') return 1;
        return in_array($v, ['1','yes','true','active','enabled','on'], true) ? 1 : 0;
    }
}
if (!function_exists('sup_build_supplier_import_preview')) {
    function sup_build_supplier_import_preview(PDO $pdo, array $rawRows, bool $updateExisting): array {
        if (count($rawRows) < 2) {
            throw new RuntimeException('The import file is empty. Please include a header row and at least one supplier row.');
        }

        $headers = array_shift($rawRows);
        $cleanHeaders = [];
        foreach ($headers as $i => $header) {
            $cleanHeaders[(int)$i] = sup_clean_header($header);
        }

        $aliases = sup_import_aliases();
        $supplierNameHeaderFound = false;
        foreach ($aliases['supplier_name'] as $alias) {
            if (in_array(sup_clean_header($alias), $cleanHeaders, true)) {
                $supplierNameHeaderFound = true;
                break;
            }
        }
        if (!$supplierNameHeaderFound) {
            throw new RuntimeException('Preview failed: supplier_name / supplier name column is required. Download the template if unsure.');
        }

        $findByCode = $pdo->prepare('SELECT id, supplier_name FROM inventory_suppliers WHERE supplier_code = :supplier_code LIMIT 1');
        $findByName = $pdo->prepare('SELECT id, supplier_name FROM inventory_suppliers WHERE supplier_name = :supplier_name LIMIT 1');

        $seenCodes = [];
        $seenNames = [];
        $previewRows = [];
        $summary = ['total'=>0,'create'=>0,'update'=>0,'skip'=>0,'error'=>0];

        foreach ($rawRows as $lineNo => $row) {
            $realLine = $lineNo + 2;
            $mapped = [];
            foreach ($cleanHeaders as $i => $headerKey) {
                if ($headerKey !== '') $mapped[$headerKey] = trim((string)($row[$i] ?? ''));
            }

            $supplierName = sup_get_cell($mapped, $aliases, 'supplier_name');
            $supplierCode = strtoupper(sup_get_cell($mapped, $aliases, 'supplier_code'));
            $contactPerson = sup_get_cell($mapped, $aliases, 'contact_person');
            $phone = sup_get_cell($mapped, $aliases, 'phone');
            $email = sup_get_cell($mapped, $aliases, 'email');
            $address = sup_get_cell($mapped, $aliases, 'address');
            $paymentTerms = sup_get_cell($mapped, $aliases, 'payment_terms');
            $taxNumber = sup_get_cell($mapped, $aliases, 'tax_number');
            $notes = sup_get_cell($mapped, $aliases, 'notes');
            $activeRaw = sup_get_cell($mapped, $aliases, 'is_active');
            $isActive = sup_normalize_import_bool($activeRaw);

            if ($supplierName === '' && $supplierCode === '') {
                $summary['skip']++;
                continue;
            }

            $summary['total']++;
            $issues = [];
            $existingId = 0;
            $existingName = '';
            $action = 'create';

            if ($supplierName === '') $issues[] = 'Supplier name is required';
            if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) $issues[] = 'Invalid email format';
            if ($supplierCode !== '' && isset($seenCodes[$supplierCode])) $issues[] = 'Duplicate supplier code inside this file';
            if ($supplierName !== '') {
                $nameKey = strtolower($supplierName);
                if (isset($seenNames[$nameKey])) $issues[] = 'Duplicate supplier name inside this file';
            }

            if ($supplierCode !== '') {
                $findByCode->execute([':supplier_code' => $supplierCode]);
                $found = $findByCode->fetch(PDO::FETCH_ASSOC);
                if ($found) { $existingId = (int)$found['id']; $existingName = (string)$found['supplier_name']; }
            }
            if ($existingId <= 0 && $supplierName !== '') {
                $findByName->execute([':supplier_name' => $supplierName]);
                $found = $findByName->fetch(PDO::FETCH_ASSOC);
                if ($found) { $existingId = (int)$found['id']; $existingName = (string)$found['supplier_name']; }
            }

            if ($existingId > 0) $action = $updateExisting ? 'update' : 'skip';
            if ($issues) $action = 'error';

            if ($supplierCode !== '') $seenCodes[$supplierCode] = true;
            if ($supplierName !== '') $seenNames[strtolower($supplierName)] = true;

            $summary[$action]++;
            $previewRows[] = [
                'line' => $realLine,
                'action' => $action,
                'existing_id' => $existingId,
                'existing_name' => $existingName,
                'issues' => $issues,
                'data' => [
                    'supplier_code' => $supplierCode,
                    'supplier_name' => $supplierName,
                    'contact_person' => $contactPerson,
                    'phone' => $phone,
                    'email' => $email,
                    'address' => $address,
                    'payment_terms' => $paymentTerms,
                    'tax_number' => $taxNumber,
                    'notes' => $notes,
                    'is_active' => $isActive,
                ]
            ];
        }

        return [
            'token' => bin2hex(random_bytes(16)),
            'created_at' => date('Y-m-d H:i:s'),
            'update_existing' => $updateExisting ? 1 : 0,
            'summary' => $summary,
            'rows' => $previewRows,
        ];
    }
}

$errors = [];

try {
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS inventory_suppliers (
            id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
            supplier_code VARCHAR(60) NULL,
            supplier_name VARCHAR(180) NOT NULL,
            contact_person VARCHAR(150) NULL,
            phone VARCHAR(80) NULL,
            email VARCHAR(150) NULL,
            address TEXT NULL,
            payment_terms VARCHAR(120) NULL,
            tax_number VARCHAR(120) NULL,
            notes TEXT NULL,
            is_active TINYINT(1) NOT NULL DEFAULT 1,
            created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            UNIQUE KEY uq_inventory_supplier_name (supplier_name),
            UNIQUE KEY uq_inventory_supplier_code (supplier_code),
            INDEX idx_inventory_supplier_active (is_active)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");



    $pdo->exec("
        CREATE TABLE IF NOT EXISTS supplier_payment_terms (
            id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
            term_code VARCHAR(30) NOT NULL,
            term_name VARCHAR(120) NOT NULL,
            days_due INT UNSIGNED NOT NULL DEFAULT 0,
            description VARCHAR(255) NULL,
            is_active TINYINT(1) NOT NULL DEFAULT 1,
            created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            UNIQUE KEY uq_supplier_payment_terms_code (term_code),
            UNIQUE KEY uq_supplier_payment_terms_name (term_name),
            INDEX idx_supplier_payment_terms_active (is_active),
            INDEX idx_supplier_payment_terms_days (days_due)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");

    $seedTerms = [
        ['CASH', 'Cash', 0, 'Payment due immediately.'],
        ['COD', 'Cash on Delivery', 0, 'Payment due when goods are delivered.'],
        ['PREPAY', 'Prepayment', 0, 'Payment required before delivery or supply.'],
        ['NET7', '7 Days', 7, 'Payment due within 7 days.'],
        ['NET14', '14 Days', 14, 'Payment due within 14 days.'],
        ['NET30', '30 Days', 30, 'Payment due within 30 days.'],
        ['NET45', '45 Days', 45, 'Payment due within 45 days.'],
        ['NET60', '60 Days', 60, 'Payment due within 60 days.'],
        ['NET90', '90 Days', 90, 'Payment due within 90 days.'],
        ['ACCOUNT', 'On Account', 30, 'Supplier is handled on account / statement.'],
    ];
    $stmtTermSeed = $pdo->prepare("
        INSERT INTO supplier_payment_terms (term_code, term_name, days_due, description, is_active)
        VALUES (:term_code, :term_name, :days_due, :description, 1)
        ON DUPLICATE KEY UPDATE
            term_name = VALUES(term_name),
            days_due = VALUES(days_due),
            description = VALUES(description),
            is_active = 1
    ");
    foreach ($seedTerms as $term) {
        $stmtTermSeed->execute([
            ':term_code' => $term[0],
            ':term_name' => $term[1],
            ':days_due' => $term[2],
            ':description' => $term[3],
        ]);
    }

    $colCheck = $pdo->prepare("
        SELECT COUNT(*)
        FROM information_schema.columns
        WHERE table_schema = DATABASE()
          AND table_name = 'inventory_suppliers'
          AND column_name = :col
    ");

    foreach ([
        'supplier_code' => "ALTER TABLE inventory_suppliers ADD COLUMN supplier_code VARCHAR(60) NULL AFTER id",
        'contact_person' => "ALTER TABLE inventory_suppliers ADD COLUMN contact_person VARCHAR(150) NULL AFTER supplier_name",
        'payment_terms' => "ALTER TABLE inventory_suppliers ADD COLUMN payment_terms VARCHAR(120) NULL AFTER address",
        'payment_terms_id' => "ALTER TABLE inventory_suppliers ADD COLUMN payment_terms_id INT UNSIGNED NULL AFTER payment_terms",
        'tax_number' => "ALTER TABLE inventory_suppliers ADD COLUMN tax_number VARCHAR(120) NULL AFTER payment_terms_id",
        'notes' => "ALTER TABLE inventory_suppliers ADD COLUMN notes TEXT NULL AFTER tax_number"
    ] as $col => $sql) {
        $colCheck->execute([':col' => $col]);
        if ((int)$colCheck->fetchColumn() === 0) {
            $pdo->exec($sql);
        }
    }

    $pdo->exec("
        CREATE TABLE IF NOT EXISTS store_locations (
            id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
            location_code VARCHAR(50) NULL,
            location_name VARCHAR(150) NOT NULL,
            location_type ENUM('main_store','bar','restaurant','curio','kitchen','housekeeping','maintenance','other') NOT NULL DEFAULT 'main_store',
            is_pos_location TINYINT(1) NOT NULL DEFAULT 0,
            allow_room_charge TINYINT(1) NOT NULL DEFAULT 1,
            is_active TINYINT(1) NOT NULL DEFAULT 1,
            notes TEXT NULL,
            created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            UNIQUE KEY uq_store_location_code (location_code)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");

    $pdo->exec("
        CREATE TABLE IF NOT EXISTS inventory_grns (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
            grn_no VARCHAR(60) NOT NULL,
            supplier_id INT UNSIGNED NULL,
            supplier_name VARCHAR(180) NULL,
            store_id INT UNSIGNED NOT NULL,
            invoice_no VARCHAR(100) NULL,
            grn_date DATE NOT NULL,
            subtotal DECIMAL(14,2) NOT NULL DEFAULT 0.00,
            tax_amount DECIMAL(14,2) NOT NULL DEFAULT 0.00,
            total_amount DECIMAL(14,2) NOT NULL DEFAULT 0.00,
            status ENUM('posted','void') NOT NULL DEFAULT 'posted',
            notes TEXT NULL,
            created_by INT UNSIGNED NULL,
            void_reason TEXT NULL,
            voided_at DATETIME NULL,
            created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            UNIQUE KEY uq_grn_no (grn_no),
            INDEX idx_grn_supplier (supplier_id),
            INDEX idx_grn_store (store_id),
            INDEX idx_grn_date (grn_date)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
} catch (Throwable $e) {
    $errors[] = 'Could not prepare supplier tables: ' . $e->getMessage();
}


if (isset($_GET['download_import_template'])) {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="supplier_import_template.csv"');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['supplier_code','supplier_name','contact_person','phone','email','address','payment_terms','tax_number','notes','is_active']);
    fputcsv($out, ['SUP-001','Example Supplier','John Smith','+263 77 000 0000','supplier@example.com','123 Main Road','30 days','VAT123456','Opening balance supplier','1']);
    fclose($out);
    exit;
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        if (function_exists('verify_csrf')) verify_csrf();

        $action = (string)($_POST['action'] ?? '');


        if ($action === 'preview_supplier_import') {
            $updateExisting = sup_bool($_POST['update_existing'] ?? 0) === 1;
            $rows = sup_read_import_rows($_FILES['supplier_import_file'] ?? []);
            $preview = sup_build_supplier_import_preview($pdo, $rows, $updateExisting);
            $_SESSION['supplier_import_preview'] = $preview;
            sup_flash('info', 'Import preview prepared. Review the rows below, then confirm to save valid records.');
            header('Location: suppliers.php#importPreview');
            exit;
        }

        if ($action === 'clear_supplier_import_preview') {
            unset($_SESSION['supplier_import_preview']);
            sup_flash('info', 'Supplier import preview cleared.');
            header('Location: suppliers.php#supplierImport');
            exit;
        }

        if ($action === 'confirm_supplier_import') {
            $preview = $_SESSION['supplier_import_preview'] ?? null;
            $postedToken = (string)($_POST['import_token'] ?? '');
            if (!$preview || !is_array($preview) || !hash_equals((string)($preview['token'] ?? ''), $postedToken)) {
                throw new RuntimeException('Import preview expired or invalid. Please upload the file again.');
            }

            $insertStmt = $pdo->prepare("\n                INSERT INTO inventory_suppliers\n                (supplier_code, supplier_name, contact_person, phone, email, address, payment_terms, payment_terms_id, tax_number, notes, is_active)\n                VALUES\n                (:supplier_code, :supplier_name, :contact_person, :phone, :email, :address, :payment_terms, :payment_terms_id, :tax_number, :notes, :is_active)\n            ");
            $updateStmt = $pdo->prepare("\n                UPDATE inventory_suppliers\n                SET supplier_code = :supplier_code,\n                    supplier_name = :supplier_name,\n                    contact_person = :contact_person,\n                    phone = :phone,\n                    email = :email,\n                    address = :address,\n                    payment_terms = :payment_terms,\n                    tax_number = :tax_number,\n                    notes = :notes,\n                    is_active = :is_active\n                WHERE id = :id\n            ");

            $created = 0; $updated = 0; $skipped = 0; $failed = 0;
            $messages = [];
            $pdo->beginTransaction();

            foreach (($preview['rows'] ?? []) as $item) {
                $actionRow = (string)($item['action'] ?? 'skip');
                $line = (int)($item['line'] ?? 0);
                $data = $item['data'] ?? [];

                if ($actionRow === 'skip' || $actionRow === 'error') { $skipped++; continue; }

                $payload = [
                    ':supplier_code' => ($data['supplier_code'] ?? '') !== '' ? $data['supplier_code'] : null,
                    ':supplier_name' => $data['supplier_name'] ?? '',
                    ':contact_person' => ($data['contact_person'] ?? '') !== '' ? $data['contact_person'] : null,
                    ':phone' => ($data['phone'] ?? '') !== '' ? $data['phone'] : null,
                    ':email' => ($data['email'] ?? '') !== '' ? $data['email'] : null,
                    ':address' => ($data['address'] ?? '') !== '' ? $data['address'] : null,
                    ':payment_terms' => ($data['payment_terms'] ?? '') !== '' ? $data['payment_terms'] : null,
                    ':payment_terms_id' => null,
                    ':tax_number' => ($data['tax_number'] ?? '') !== '' ? $data['tax_number'] : null,
                    ':notes' => ($data['notes'] ?? '') !== '' ? $data['notes'] : null,
                    ':is_active' => (int)($data['is_active'] ?? 1),
                ];

                $importTermText = (string)($data['payment_terms'] ?? '');
                if ($importTermText !== '') {
                    $matchedTerm = sup_payment_term_by_text($pdo, $importTermText);
                    if ($matchedTerm) {
                        $payload[':payment_terms'] = (string)$matchedTerm['term_name'];
                        $payload[':payment_terms_id'] = (int)$matchedTerm['id'];
                    }
                }

                try {
                    if ($actionRow === 'update') {
                        $existingId = (int)($item['existing_id'] ?? 0);
                        if ($existingId <= 0) { $failed++; $messages[] = "Line {$line}: update target missing."; continue; }
                        $payload[':id'] = $existingId;
                        $updateStmt->execute($payload);
                        $updated++;
                    } elseif ($actionRow === 'create') {
                        $insertStmt->execute($payload);
                        $created++;
                    }
                } catch (Throwable $rowError) {
                    $failed++;
                    $messages[] = "Line {$line}: " . $rowError->getMessage();
                }
            }

            $pdo->commit();
            unset($_SESSION['supplier_import_preview']);

            $summaryMsg = "Supplier import saved. Created: {$created}. Updated: {$updated}. Skipped: {$skipped}. Failed: {$failed}.";
            if ($messages) $summaryMsg .= ' ' . implode(' ', array_slice($messages, 0, 4));
            sup_flash($failed > 0 ? 'warning' : 'success', $summaryMsg);
            header('Location: suppliers.php');
            exit;
        }

        if ($action === 'save_supplier') {
            $id = (int)($_POST['id'] ?? 0);
            $supplierCode = strtoupper(trim((string)($_POST['supplier_code'] ?? '')));
            $supplierName = trim((string)($_POST['supplier_name'] ?? ''));
            $contactPerson = trim((string)($_POST['contact_person'] ?? ''));
            $phone = trim((string)($_POST['phone'] ?? ''));
            $email = trim((string)($_POST['email'] ?? ''));
            $address = trim((string)($_POST['address'] ?? ''));
            $paymentTermsId = (int)($_POST['payment_terms_id'] ?? 0);
            $paymentTerms = '';
            $taxNumber = trim((string)($_POST['tax_number'] ?? ''));
            $notes = trim((string)($_POST['notes'] ?? ''));
            $isActive = sup_bool($_POST['is_active'] ?? 0);

            if ($supplierName === '') {
                throw new RuntimeException('Supplier name is required.');
            }

            if ($paymentTermsId > 0) {
                $termRow = sup_payment_term_by_id($pdo, $paymentTermsId);
                if (!$termRow) {
                    throw new RuntimeException('Selected payment terms are invalid or inactive.');
                }
                $paymentTerms = (string)$termRow['term_name'];
            } else {
                $paymentTermsId = 0;
                $paymentTerms = '';
            }

            if ($supplierCode === '') {
                $prefix = strtoupper(substr(preg_replace('/[^A-Za-z0-9]/', '', $supplierName), 0, 4));
                $supplierCode = ($prefix ?: 'SUP') . '-' . date('His');
            }

            $payload = [
                ':supplier_code' => $supplierCode,
                ':supplier_name' => $supplierName,
                ':contact_person' => $contactPerson ?: null,
                ':phone' => $phone ?: null,
                ':email' => $email ?: null,
                ':address' => $address ?: null,
                ':payment_terms' => $paymentTerms ?: null,
                ':payment_terms_id' => $paymentTermsId > 0 ? $paymentTermsId : null,
                ':tax_number' => $taxNumber ?: null,
                ':notes' => $notes ?: null,
                ':is_active' => $isActive,
            ];

            if ($id > 0) {
                $payload[':id'] = $id;
                $stmt = $pdo->prepare("
                    UPDATE inventory_suppliers
                    SET supplier_code = :supplier_code,
                        supplier_name = :supplier_name,
                        contact_person = :contact_person,
                        phone = :phone,
                        email = :email,
                        address = :address,
                        payment_terms = :payment_terms,
                        payment_terms_id = :payment_terms_id,
                        tax_number = :tax_number,
                        notes = :notes,
                        is_active = :is_active
                    WHERE id = :id
                ");
                $stmt->execute($payload);
                sup_flash('success', 'Supplier updated successfully.');
            } else {
                $stmt = $pdo->prepare("
                    INSERT INTO inventory_suppliers
                    (supplier_code, supplier_name, contact_person, phone, email, address, payment_terms, payment_terms_id, tax_number, notes, is_active)
                    VALUES
                    (:supplier_code, :supplier_name, :contact_person, :phone, :email, :address, :payment_terms, :payment_terms_id, :tax_number, :notes, :is_active)
                ");
                $stmt->execute($payload);
                sup_flash('success', 'Supplier created successfully.');
            }

            header('Location: suppliers.php');
            exit;
        }

        if ($action === 'toggle_supplier') {
            $id = (int)($_POST['id'] ?? 0);
            if ($id <= 0) throw new RuntimeException('Invalid supplier selected.');

            $stmt = $pdo->prepare("
                UPDATE inventory_suppliers
                SET is_active = CASE WHEN is_active = 1 THEN 0 ELSE 1 END
                WHERE id = :id
            ");
            $stmt->execute([':id' => $id]);

            sup_flash('success', 'Supplier status updated.');
            header('Location: suppliers.php');
            exit;
        }

        if ($action === 'delete_supplier') {
            $id = (int)($_POST['id'] ?? 0);
            if ($id <= 0) throw new RuntimeException('Invalid supplier selected.');

            $stmt = $pdo->prepare("SELECT COUNT(*) FROM inventory_grns WHERE supplier_id = :id");
            $stmt->execute([':id' => $id]);

            if ((int)$stmt->fetchColumn() > 0) {
                $stmt = $pdo->prepare("UPDATE inventory_suppliers SET is_active = 0 WHERE id = :id");
                $stmt->execute([':id' => $id]);
                sup_flash('warning', 'Supplier has GRNs, so it was deactivated instead of deleted.');
            } else {
                $stmt = $pdo->prepare("DELETE FROM inventory_suppliers WHERE id = :id");
                $stmt->execute([':id' => $id]);
                sup_flash('success', 'Supplier deleted successfully.');
            }

            header('Location: suppliers.php');
            exit;
        }

    } catch (Throwable $e) {
        sup_flash('danger', $e->getMessage());
        header('Location: suppliers.php');
        exit;
    }
}


$paymentTermsList = [];
try {
    $paymentTermsList = $pdo->query("
        SELECT id, term_code, term_name, days_due, description
        FROM supplier_payment_terms
        WHERE is_active = 1
        ORDER BY days_due ASC, term_name ASC
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $errors[] = 'Could not load payment terms: ' . $e->getMessage();
}

$editId = (int)($_GET['edit_id'] ?? 0);
$editSupplier = null;

if ($editId > 0) {
    try {
        $stmt = $pdo->prepare("SELECT s.*, COALESCE(pt.term_name, s.payment_terms, '') AS payment_terms_label FROM inventory_suppliers s LEFT JOIN supplier_payment_terms pt ON pt.id = s.payment_terms_id WHERE s.id = :id LIMIT 1");
        $stmt->execute([':id' => $editId]);
        $editSupplier = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    } catch (Throwable $e) {}
}

$status = trim((string)($_GET['status'] ?? ''));
$search = trim((string)($_GET['q'] ?? ''));

$where = "1=1";
$params = [];

if ($status !== '') {
    $where .= " AND s.is_active = :is_active";
    $params[':is_active'] = (int)$status;
}

if ($search !== '') {
    $where .= " AND (
        s.supplier_name LIKE :q_name
        OR s.supplier_code LIKE :q_code
        OR s.contact_person LIKE :q_contact
        OR s.phone LIKE :q_phone
        OR s.email LIKE :q_email
        OR s.tax_number LIKE :q_tax
    )";

    $likeSearch = '%' . $search . '%';
    $params[':q_name'] = $likeSearch;
    $params[':q_code'] = $likeSearch;
    $params[':q_contact'] = $likeSearch;
    $params[':q_phone'] = $likeSearch;
    $params[':q_email'] = $likeSearch;
    $params[':q_tax'] = $likeSearch;
}
if (isset($_GET['export_suppliers'])) {
    try {
        $exportSql = "
            SELECT
                s.supplier_code,
                s.supplier_name,
                s.contact_person,
                s.phone,
                s.email,
                s.address,
                COALESCE(pt.term_name, s.payment_terms, '') AS payment_terms,
                s.tax_number,
                s.notes,
                CASE WHEN s.is_active = 1 THEN 'Active' ELSE 'Inactive' END AS status_label,
                COALESCE(g.grn_count, 0) AS grn_count,
                COALESCE(g.purchase_total, 0) AS purchase_total,
                COALESCE(g.void_total, 0) AS void_total,
                g.last_grn_date
            FROM inventory_suppliers s
            LEFT JOIN (
                SELECT
                    supplier_id,
                    COUNT(*) AS grn_count,
                    SUM(CASE WHEN status = 'posted' THEN total_amount ELSE 0 END) AS purchase_total,
                    SUM(CASE WHEN status = 'void' THEN total_amount ELSE 0 END) AS void_total,
                    MAX(grn_date) AS last_grn_date
                FROM inventory_grns
                WHERE supplier_id IS NOT NULL
                GROUP BY supplier_id
            ) g ON g.supplier_id = s.id
            LEFT JOIN supplier_payment_terms pt ON pt.id = s.payment_terms_id
            WHERE $where
            ORDER BY s.is_active DESC, s.supplier_name ASC
        ";
        $stmt = $pdo->prepare($exportSql);
        $stmt->execute($params);
        $exportRows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $filename = 'suppliers_export_' . date('Ymd_His') . '.xls';
        header('Content-Type: application/vnd.ms-excel; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Pragma: no-cache');
        header('Expires: 0');

        echo "\xEF\xBB\xBF";
        echo '<table border="1">';
        echo '<tr>';
        foreach (['Supplier Code','Supplier Name','Contact Person','Phone','Email','Address','Payment Terms','Tax Number','Notes','Status','GRNs','Purchases','Voids','Last GRN'] as $heading) {
            echo '<th style="background:#f3f4f6;font-weight:bold;">' . h($heading) . '</th>';
        }
        echo '</tr>';

        foreach ($exportRows as $row) {
            echo '<tr>';
            echo '<td>' . h($row['supplier_code'] ?? '') . '</td>';
            echo '<td>' . h($row['supplier_name'] ?? '') . '</td>';
            echo '<td>' . h($row['contact_person'] ?? '') . '</td>';
            echo '<td>' . h($row['phone'] ?? '') . '</td>';
            echo '<td>' . h($row['email'] ?? '') . '</td>';
            echo '<td>' . h($row['address'] ?? '') . '</td>';
            echo '<td>' . h($row['payment_terms'] ?? '') . '</td>';
            echo '<td>' . h($row['tax_number'] ?? '') . '</td>';
            echo '<td>' . h($row['notes'] ?? '') . '</td>';
            echo '<td>' . h($row['status_label'] ?? '') . '</td>';
            echo '<td style="mso-number-format:\'0\';">' . (int)($row['grn_count'] ?? 0) . '</td>';
            echo '<td style="mso-number-format:\'#,##0.00\';">' . number_format((float)($row['purchase_total'] ?? 0), 2, '.', '') . '</td>';
            echo '<td style="mso-number-format:\'#,##0.00\';">' . number_format((float)($row['void_total'] ?? 0), 2, '.', '') . '</td>';
            echo '<td>' . h($row['last_grn_date'] ?? '') . '</td>';
            echo '</tr>';
        }
        echo '</table>';
        exit;
    } catch (Throwable $e) {
        sup_flash('danger', 'Supplier export failed: ' . $e->getMessage());
        header('Location: suppliers.php');
        exit;
    }
}

$suppliers = [];
$summary = [
    'total' => 0,
    'active' => 0,
    'inactive' => 0,
    'grns' => 0,
    'purchase_total' => 0,
    'void_total' => 0,
];

try {
    $stmt = $pdo->prepare("
        SELECT
            s.*,
            COALESCE(pt.term_name, s.payment_terms, '') AS payment_terms_label,
            pt.term_code AS payment_terms_code,
            pt.days_due AS payment_terms_days,
            COALESCE(g.grn_count, 0) AS grn_count,
            COALESCE(g.purchase_total, 0) AS purchase_total,
            COALESCE(g.void_total, 0) AS void_total,
            g.last_grn_date
        FROM inventory_suppliers s
        LEFT JOIN (
            SELECT
                supplier_id,
                COUNT(*) AS grn_count,
                SUM(CASE WHEN status = 'posted' THEN total_amount ELSE 0 END) AS purchase_total,
                SUM(CASE WHEN status = 'void' THEN total_amount ELSE 0 END) AS void_total,
                MAX(grn_date) AS last_grn_date
            FROM inventory_grns
            WHERE supplier_id IS NOT NULL
            GROUP BY supplier_id
        ) g ON g.supplier_id = s.id
        LEFT JOIN supplier_payment_terms pt ON pt.id = s.payment_terms_id
        WHERE $where
        ORDER BY s.is_active DESC, s.supplier_name ASC
        LIMIT 500
    ");
    $stmt->execute($params);
    $suppliers = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($suppliers as $row) {
        $summary['total']++;
        if ((int)$row['is_active'] === 1) $summary['active']++;
        else $summary['inactive']++;
        $summary['grns'] += (int)$row['grn_count'];
        $summary['purchase_total'] += (float)$row['purchase_total'];
        $summary['void_total'] += (float)$row['void_total'];
    }
} catch (Throwable $e) {
    $errors[] = 'Could not load suppliers: ' . $e->getMessage();
}

$viewId = (int)($_GET['view_id'] ?? 0);
$viewSupplier = null;
$recentGrns = [];

if ($viewId > 0) {
    try {
        $stmt = $pdo->prepare("SELECT s.*, COALESCE(pt.term_name, s.payment_terms, '') AS payment_terms_label FROM inventory_suppliers s LEFT JOIN supplier_payment_terms pt ON pt.id = s.payment_terms_id WHERE s.id = :id LIMIT 1");
        $stmt->execute([':id' => $viewId]);
        $viewSupplier = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;

        if ($viewSupplier) {
            $stmt = $pdo->prepare("
                SELECT g.*, sl.location_name
                FROM inventory_grns g
                LEFT JOIN store_locations sl ON sl.id = g.store_id
                WHERE g.supplier_id = :supplier_id
                ORDER BY g.grn_date DESC, g.id DESC
                LIMIT 20
            ");
            $stmt->execute([':supplier_id' => $viewId]);
            $recentGrns = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
    } catch (Throwable $e) {
        $errors[] = 'Could not load supplier detail: ' . $e->getMessage();
    }
}

$importPreview = $_SESSION['supplier_import_preview'] ?? null;
$flashes = sup_get_flash();

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="hero-band">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-truck"></i> Stores &amp; POS Inventory</div>
            <div class="hero-title mt-2">Suppliers</div>
            <div class="hero-subtitle mt-2">
                Manage supplier master records used for GRNs, purchases and future supplier payments.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <div class="d-inline-flex gap-2 flex-wrap justify-content-lg-end supplier-hero-actions">
                <a href="#supplierImport" class="btn btn-warning">
                    <i class="bi bi-upload me-2"></i>Import Suppliers
                </a>
                <a href="suppliers.php?<?php echo h(http_build_query(array_merge($_GET, ['export_suppliers' => 1, 'edit_id' => null, 'view_id' => null]))); ?>" class="btn btn-success">
                    <i class="bi bi-file-earmark-excel me-2"></i>Export Excel
                </a>
                <a href="grn.php" class="btn btn-light">
                    <i class="bi bi-receipt me-2"></i>GRN / Purchases
                </a>
                <a href="stock_movements.php" class="btn btn-outline-light">
                    <i class="bi bi-arrow-left-right me-2"></i>Movements
                </a>
            </div>
        </div>
    </div>
</div>

<?php foreach ($flashes as $flash): ?>
    <div class="alert alert-<?php echo h($flash['type']); ?>"><?php echo h($flash['message']); ?></div>
<?php endforeach; ?>

<?php if ($errors): ?>
    <div class="alert alert-danger">
        <div class="fw-bold mb-2">Please fix the following:</div>
        <ul class="mb-0"><?php foreach ($errors as $err): ?><li><?php echo h($err); ?></li><?php endforeach; ?></ul>
    </div>
<?php endif; ?>

<div class="row g-4 mb-4">
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-primary-subtle text-primary"><i class="bi bi-people"></i></div>
            <div><div class="metric-label">Suppliers</div><div class="metric-value"><?php echo (int)$summary['total']; ?></div></div>
        </div>
    </div>
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-success-subtle text-success"><i class="bi bi-check-circle"></i></div>
            <div><div class="metric-label">Active</div><div class="metric-value"><?php echo (int)$summary['active']; ?></div></div>
        </div>
    </div>
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-info-subtle text-info"><i class="bi bi-receipt"></i></div>
            <div><div class="metric-label">GRNs</div><div class="metric-value"><?php echo (int)$summary['grns']; ?></div></div>
        </div>
    </div>
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-warning-subtle text-warning"><i class="bi bi-cash-stack"></i></div>
            <div><div class="metric-label">Purchases</div><div class="metric-value small-value"><?php echo money_fmt($summary['purchase_total']); ?></div></div>
        </div>
    </div>
</div>

<?php if ($viewSupplier): ?>
<div class="card panel-card mb-4 supplier-view">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><?php echo h($viewSupplier['supplier_name']); ?></h5>
        <a href="suppliers.php" class="btn btn-sm btn-outline-secondary">Close</a>
    </div>
    <div class="card-body">
        <div class="row g-3 mb-3">
            <div class="col-md-3"><strong>Code:</strong><br><?php echo h($viewSupplier['supplier_code'] ?: '—'); ?></div>
            <div class="col-md-3"><strong>Contact:</strong><br><?php echo h($viewSupplier['contact_person'] ?: '—'); ?></div>
            <div class="col-md-3"><strong>Phone:</strong><br><?php echo h($viewSupplier['phone'] ?: '—'); ?></div>
            <div class="col-md-3"><strong>Email:</strong><br><?php echo h($viewSupplier['email'] ?: '—'); ?></div>
            <div class="col-md-3"><strong>Payment Terms:</strong><br><?php echo h(($viewSupplier['payment_terms_label'] ?? $viewSupplier['payment_terms'] ?? '') ?: '—'); ?></div>
            <div class="col-md-3"><strong>Tax Number:</strong><br><?php echo h($viewSupplier['tax_number'] ?: '—'); ?></div>
            <div class="col-md-3"><strong>Status:</strong><br>
                <span class="badge <?php echo (int)$viewSupplier['is_active'] === 1 ? 'text-bg-success' : 'text-bg-secondary'; ?>">
                    <?php echo (int)$viewSupplier['is_active'] === 1 ? 'Active' : 'Inactive'; ?>
                </span>
            </div>
        </div>

        <?php if (!empty($viewSupplier['address'])): ?>
            <div class="alert alert-light border"><strong>Address:</strong><br><?php echo nl2br(h($viewSupplier['address'])); ?></div>
        <?php endif; ?>

        <?php if (!empty($viewSupplier['notes'])): ?>
            <div class="alert alert-info"><strong>Notes:</strong><br><?php echo nl2br(h($viewSupplier['notes'])); ?></div>
        <?php endif; ?>

        <h6 class="fw-bold mt-4">Recent GRNs</h6>
        <div class="table-responsive">
            <table class="table table-sm align-middle mb-0">
                <thead><tr><th>Date</th><th>GRN</th><th>Store</th><th>Invoice</th><th>Status</th><th class="text-end">Total</th><th></th></tr></thead>
                <tbody>
                <?php if (!$recentGrns): ?>
                    <tr><td colspan="7" class="text-center text-muted py-3">No GRNs for this supplier yet.</td></tr>
                <?php else: ?>
                    <?php foreach ($recentGrns as $g): ?>
                        <tr>
                            <td><?php echo h($g['grn_date']); ?></td>
                            <td><strong><?php echo h($g['grn_no']); ?></strong></td>
                            <td><?php echo h($g['location_name'] ?: 'Store'); ?></td>
                            <td><?php echo h($g['invoice_no'] ?: '—'); ?></td>
                            <td><span class="badge <?php echo $g['status'] === 'posted' ? 'text-bg-success' : 'text-bg-danger'; ?>"><?php echo h(ucwords($g['status'])); ?></span></td>
                            <td class="text-end fw-bold"><?php echo money_fmt($g['total_amount']); ?></td>
                            <td class="text-end"><a href="grn.php?view_id=<?php echo (int)$g['id']; ?>" class="btn btn-sm btn-outline-primary"><i class="bi bi-eye"></i></a></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php endif; ?>

<div class="row g-4">
    <div class="col-xl-4">
        <div class="card panel-card">
            <div class="card-header">
                <h5 class="mb-0"><?php echo $editSupplier ? 'Edit Supplier' : 'Add Supplier'; ?></h5>
            </div>
            <div class="card-body">
                <form method="post">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="save_supplier">
                    <input type="hidden" name="id" value="<?php echo (int)($editSupplier['id'] ?? 0); ?>">

                    <div class="row g-3">
                        <div class="col-md-5">
                            <label class="form-label">Supplier Code</label>
                            <input type="text" name="supplier_code" class="form-control" value="<?php echo h($editSupplier['supplier_code'] ?? ''); ?>" placeholder="Auto if blank">
                        </div>
                        <div class="col-md-7">
                            <label class="form-label">Supplier Name</label>
                            <input type="text" name="supplier_name" class="form-control" required value="<?php echo h($editSupplier['supplier_name'] ?? ''); ?>">
                        </div>
                    </div>

                    <div class="mt-3">
                        <label class="form-label">Contact Person</label>
                        <input type="text" name="contact_person" class="form-control" value="<?php echo h($editSupplier['contact_person'] ?? ''); ?>">
                    </div>

                    <div class="row g-3 mt-0">
                        <div class="col-md-6">
                            <label class="form-label">Phone</label>
                            <input type="text" name="phone" class="form-control" value="<?php echo h($editSupplier['phone'] ?? ''); ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Email</label>
                            <input type="email" name="email" class="form-control" value="<?php echo h($editSupplier['email'] ?? ''); ?>">
                        </div>
                    </div>

                    <div class="row g-3 mt-0">
                        <div class="col-md-6">
                            <label class="form-label">Payment Terms</label>
                            <select name="payment_terms_id" class="form-select">
                                <option value="0">Select payment terms</option>
                                <?php foreach ($paymentTermsList as $term): ?>
                                    <?php
                                        $termId = (int)$term['id'];
                                        $selectedTermId = (int)($editSupplier['payment_terms_id'] ?? 0);
                                        $legacyTerm = trim((string)($editSupplier['payment_terms'] ?? ''));
                                        $isSelected = $selectedTermId === $termId || ($selectedTermId <= 0 && $legacyTerm !== '' && strcasecmp($legacyTerm, (string)$term['term_name']) === 0);
                                    ?>
                                    <option value="<?php echo $termId; ?>" <?php echo $isSelected ? 'selected' : ''; ?>>
                                        <?php echo h($term['term_name']); ?><?php echo (int)$term['days_due'] > 0 ? ' - ' . (int)$term['days_due'] . ' days' : ''; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Tax Number</label>
                            <input type="text" name="tax_number" class="form-control" value="<?php echo h($editSupplier['tax_number'] ?? ''); ?>">
                        </div>
                    </div>

                    <div class="mt-3">
                        <label class="form-label">Address</label>
                        <textarea name="address" class="form-control" rows="3"><?php echo h($editSupplier['address'] ?? ''); ?></textarea>
                    </div>

                    <div class="mt-3">
                        <label class="form-label">Notes</label>
                        <textarea name="notes" class="form-control" rows="3"><?php echo h($editSupplier['notes'] ?? ''); ?></textarea>
                    </div>

                    <label class="setting-check mt-3">
                        <input type="checkbox" name="is_active" value="1" <?php echo (int)($editSupplier['is_active'] ?? 1) === 1 ? 'checked' : ''; ?>>
                        <span>Active Supplier</span>
                    </label>

                    <div class="d-grid gap-2 mt-4">
                        <button class="btn btn-primary">
                            <i class="bi bi-save me-2"></i><?php echo $editSupplier ? 'Update Supplier' : 'Create Supplier'; ?>
                        </button>
                        <?php if ($editSupplier): ?>
                            <a href="suppliers.php" class="btn btn-outline-secondary">Cancel Edit</a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="col-xl-8">

        <div class="card panel-card mb-4" id="supplierImport">
            <div class="card-header d-flex justify-content-between align-items-center">
                <div>
                    <h5 class="mb-0"><i class="bi bi-upload me-2"></i>Import Suppliers</h5>
                    <div class="small text-muted mt-1">Upload first, review the preview, then confirm. Nothing is saved until confirmation.</div>
                </div>
                <a href="suppliers.php?download_import_template=1" class="btn btn-sm btn-outline-primary">
                    <i class="bi bi-download me-1"></i>Download Template
                </a>
            </div>
            <div class="card-body">
                <form method="post" enctype="multipart/form-data" class="row g-3 align-items-end import-uploader">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="preview_supplier_import">

                    <div class="col-lg-6">
                        <label class="form-label">CSV / Excel File</label>
                        <input type="file" name="supplier_import_file" class="form-control" accept=".csv,.txt,.xlsx" required>
                        <div class="form-text">Required column: <strong>supplier_name</strong>. Accepted aliases: Supplier, Vendor, Name, Company.</div>
                    </div>

                    <div class="col-lg-3">
                        <label class="setting-check mb-0">
                            <input type="checkbox" name="update_existing" value="1" checked>
                            <span>Allow updates to existing suppliers</span>
                        </label>
                    </div>

                    <div class="col-lg-3 d-grid">
                        <button class="btn btn-primary">
                            <i class="bi bi-search me-2"></i>Preview Import
                        </button>
                    </div>
                </form>

                <div class="import-help mt-3">
                    <strong>Supported columns:</strong>
                    supplier_code, supplier_name, contact_person, phone, email, address, payment_terms, tax_number, notes, is_active.
                    Existing suppliers are matched by supplier_code first, then supplier_name.
                </div>
            </div>
        </div>

        <?php if ($importPreview && is_array($importPreview)): ?>
            <?php
                $impSummary = $importPreview['summary'] ?? ['total'=>0,'create'=>0,'update'=>0,'skip'=>0,'error'=>0];
                $impRows = $importPreview['rows'] ?? [];
                $canConfirm = ((int)($impSummary['create'] ?? 0) + (int)($impSummary['update'] ?? 0)) > 0 && (int)($impSummary['error'] ?? 0) === 0;
            ?>
            <div class="card panel-card mb-4 import-preview-card" id="importPreview">
                <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
                    <div>
                        <h5 class="mb-0"><i class="bi bi-clipboard-check me-2"></i>Import Preview</h5>
                        <div class="small text-muted mt-1">Prepared <?php echo h($importPreview['created_at'] ?? ''); ?>. Review before saving.</div>
                    </div>
                    <div class="d-flex gap-2">
                        <form method="post">
                            <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                            <input type="hidden" name="action" value="clear_supplier_import_preview">
                            <button class="btn btn-outline-secondary btn-sm"><i class="bi bi-x-circle me-1"></i>Clear Preview</button>
                        </form>
                        <form method="post" onsubmit="return confirm('Save these supplier import changes now?');">
                            <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                            <input type="hidden" name="action" value="confirm_supplier_import">
                            <input type="hidden" name="import_token" value="<?php echo h($importPreview['token'] ?? ''); ?>">
                            <button class="btn btn-success btn-sm" <?php echo $canConfirm ? '' : 'disabled'; ?>>
                                <i class="bi bi-check2-circle me-1"></i>Confirm &amp; Save Valid Rows
                            </button>
                        </form>
                    </div>
                </div>
                <div class="card-body">
                    <div class="row g-3 mb-3">
                        <div class="col-6 col-md-3 col-xl"><div class="import-stat"><span>Total Rows</span><strong><?php echo (int)($impSummary['total'] ?? 0); ?></strong></div></div>
                        <div class="col-6 col-md-3 col-xl"><div class="import-stat create"><span>New</span><strong><?php echo (int)($impSummary['create'] ?? 0); ?></strong></div></div>
                        <div class="col-6 col-md-3 col-xl"><div class="import-stat update"><span>Updates</span><strong><?php echo (int)($impSummary['update'] ?? 0); ?></strong></div></div>
                        <div class="col-6 col-md-3 col-xl"><div class="import-stat skip"><span>Skipped</span><strong><?php echo (int)($impSummary['skip'] ?? 0); ?></strong></div></div>
                        <div class="col-6 col-md-3 col-xl"><div class="import-stat error"><span>Errors</span><strong><?php echo (int)($impSummary['error'] ?? 0); ?></strong></div></div>
                    </div>

                    <?php if ((int)($impSummary['error'] ?? 0) > 0): ?>
                        <div class="alert alert-warning">
                            Fix the rows marked <strong>Error</strong> and upload again. For safety, confirmation is disabled while errors exist.
                        </div>
                    <?php elseif (!$canConfirm): ?>
                        <div class="alert alert-info mb-3">There are no new or update rows to save.</div>
                    <?php endif; ?>

                    <div class="table-responsive import-preview-table-wrap">
                        <table class="table table-sm table-modern align-middle mb-0 import-preview-table">
                            <thead>
                                <tr>
                                    <th>Line</th>
                                    <th>Status</th>
                                    <th>Supplier</th>
                                    <th>Contact</th>
                                    <th>Terms / Tax</th>
                                    <th>Active</th>
                                    <th>Issues</th>
                                </tr>
                            </thead>
                            <tbody>
                            <?php if (!$impRows): ?>
                                <tr><td colspan="7" class="text-center text-muted py-4">No preview rows found.</td></tr>
                            <?php else: ?>
                                <?php foreach ($impRows as $item): ?>
                                    <?php
                                        $rowAction = (string)($item['action'] ?? 'skip');
                                        $data = $item['data'] ?? [];
                                        $badgeClass = $rowAction === 'create' ? 'text-bg-success' : ($rowAction === 'update' ? 'text-bg-primary' : ($rowAction === 'error' ? 'text-bg-danger' : 'text-bg-secondary'));
                                        $label = $rowAction === 'create' ? 'New' : ($rowAction === 'update' ? 'Update' : ($rowAction === 'error' ? 'Error' : 'Skip'));
                                    ?>
                                    <tr class="import-row-<?php echo h($rowAction); ?>">
                                        <td class="fw-bold"><?php echo (int)($item['line'] ?? 0); ?></td>
                                        <td>
                                            <span class="badge <?php echo h($badgeClass); ?>"><?php echo h($label); ?></span>
                                            <?php if (!empty($item['existing_name'])): ?>
                                                <div class="small text-muted">Matches: <?php echo h($item['existing_name']); ?></div>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <strong><?php echo h($data['supplier_name'] ?? ''); ?></strong>
                                            <div class="small text-muted">Code: <?php echo h(($data['supplier_code'] ?? '') ?: '—'); ?></div>
                                        </td>
                                        <td>
                                            <?php echo h(($data['contact_person'] ?? '') ?: '—'); ?>
                                            <div class="small text-muted"><?php echo h(($data['phone'] ?? '') ?: ''); ?><?php if (!empty($data['email'])): ?> • <?php echo h($data['email']); ?><?php endif; ?></div>
                                        </td>
                                        <td>
                                            <?php echo h(($data['payment_terms'] ?? '') ?: '—'); ?>
                                            <div class="small text-muted">Tax: <?php echo h(($data['tax_number'] ?? '') ?: '—'); ?></div>
                                        </td>
                                        <td><?php echo (int)($data['is_active'] ?? 1) === 1 ? 'Yes' : 'No'; ?></td>
                                        <td class="small">
                                            <?php if (!empty($item['issues'])): ?>
                                                <span class="text-danger fw-bold"><?php echo h(implode('; ', $item['issues'])); ?></span>
                                            <?php elseif ($rowAction === 'skip'): ?>
                                                <span class="text-muted">Existing supplier; update not allowed.</span>
                                            <?php else: ?>
                                                <span class="text-success">Ready</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <div class="card panel-card mb-4">
            <div class="card-body">
                <form method="get" class="row g-3 align-items-end">
                    <div class="col-md-8">
                        <label class="form-label">Search</label>
                        <input type="text" name="q" class="form-control" value="<?php echo h($search); ?>" placeholder="Supplier/code/contact/phone/email/tax no">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-select">
                            <option value="">All</option>
                            <option value="1" <?php echo $status === '1' ? 'selected' : ''; ?>>Active</option>
                            <option value="0" <?php echo $status === '0' ? 'selected' : ''; ?>>Inactive</option>
                        </select>
                    </div>
                    <div class="col-md-1 d-grid">
                        <button class="btn btn-primary" title="Filter suppliers"><i class="bi bi-funnel"></i></button>
                    </div>
                    <div class="col-12 d-flex justify-content-end gap-2 supplier-filter-actions">
                        <a class="btn btn-outline-success btn-sm" href="suppliers.php?<?php echo h(http_build_query(array_merge($_GET, ['export_suppliers' => 1, 'edit_id' => null, 'view_id' => null]))); ?>">
                            <i class="bi bi-file-earmark-excel me-1"></i>Export Filtered Suppliers
                        </a>
                    </div>
                </form>
            </div>
        </div>

        <div class="card panel-card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Supplier Master</h5>
                <span class="text-muted small">Showing latest 500 matching suppliers</span>
            </div>
            <div class="card-body p-0">
                <div class="supplier-table-wrap">
    <table class="table table-modern align-middle mb-0 supplier-table">
                        <thead>
                        <tr>
                            <th>Supplier</th>
                            <th>Contact</th>
                            <th>Terms</th>
                            <th class="text-end">GRNs</th>
                            <th class="text-end">Purchases</th>
                            <th>Last GRN</th>
                            <th>Status</th>
                            <th class="text-end">Actions</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$suppliers): ?>
                            <tr><td colspan="8" class="text-center text-muted py-4">No suppliers found.</td></tr>
                        <?php else: ?>
                            <?php foreach ($suppliers as $row): ?>
                                <tr>
                                    <td>
                                        <strong><?php echo h($row['supplier_name']); ?></strong>
                                        <div class="small text-muted">
                                            Code: <?php echo h($row['supplier_code'] ?: '—'); ?>
                                            <?php if (!empty($row['tax_number'])): ?> • Tax: <?php echo h($row['tax_number']); ?><?php endif; ?>
                                        </div>
                                    </td>
                                    <td>
                                        <?php echo h($row['contact_person'] ?: '—'); ?>
                                        <div class="small text-muted">
                                            <?php echo h($row['phone'] ?: ''); ?>
                                            <?php if (!empty($row['email'])): ?> • <?php echo h($row['email']); ?><?php endif; ?>
                                        </div>
                                    </td>
                                    <td><?php echo h(($row['payment_terms_label'] ?? $row['payment_terms'] ?? '') ?: '—'); ?></td>
                                    <td class="text-end"><?php echo (int)$row['grn_count']; ?></td>
                                    <td class="text-end fw-bold"><?php echo money_fmt($row['purchase_total']); ?></td>
                                    <td><?php echo h($row['last_grn_date'] ?: '—'); ?></td>
                                    <td>
                                        <span class="badge <?php echo (int)$row['is_active'] === 1 ? 'text-bg-success' : 'text-bg-secondary'; ?>">
                                            <?php echo (int)$row['is_active'] === 1 ? 'Active' : 'Inactive'; ?>
                                        </span>
                                    </td>
                                    <td class="text-end">
                                        <div class="btn-group btn-group-sm">
                                            <a href="suppliers.php?view_id=<?php echo (int)$row['id']; ?>" class="btn btn-outline-info" title="View">
                                                <i class="bi bi-eye"></i>
                                            </a>
                                            <a href="suppliers.php?edit_id=<?php echo (int)$row['id']; ?>" class="btn btn-outline-primary" title="Edit">
                                                <i class="bi bi-pencil"></i>
                                            </a>
                                            <a href="grn.php?supplier_id=<?php echo (int)$row['id']; ?>" class="btn btn-outline-success" title="New GRN">
                                                <i class="bi bi-receipt"></i>
                                            </a>
                                            <form method="post" class="d-inline">
                                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                                <input type="hidden" name="action" value="toggle_supplier">
                                                <input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>">
                                                <button class="btn btn-outline-secondary" title="Toggle">
                                                    <i class="bi bi-toggle-on"></i>
                                                </button>
                                            </form>
                                            <form method="post" class="d-inline" onsubmit="return confirm('Delete/deactivate this supplier?');">
                                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                                <input type="hidden" name="action" value="delete_supplier">
                                                <input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>">
                                                <button class="btn btn-outline-danger" title="Delete">
                                                    <i class="bi bi-trash"></i>
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                                <?php if (!empty($row['address']) || !empty($row['notes'])): ?>
                                    <tr class="notes-row">
                                        <td colspan="8" class="small text-muted pt-0">
                                            <?php if (!empty($row['address'])): ?>
                                                <i class="bi bi-geo-alt me-1"></i><?php echo h($row['address']); ?>
                                            <?php endif; ?>
                                            <?php if (!empty($row['notes'])): ?>
                                                <span class="ms-2"><i class="bi bi-info-circle me-1"></i><?php echo h($row['notes']); ?></span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="alert alert-info mt-4">
            <strong>Next workflow:</strong> Use suppliers in <a href="grn.php">GRN / Purchases</a>. Later we can add supplier ledger and payments for accounts payable.
        </div>
    </div>
</div>

<style>
.small-value{font-size:1rem!important;letter-spacing:0!important}
.setting-check{display:flex;align-items:center;gap:8px;border:1px solid rgba(15,23,42,.10);background:#fff;border-radius:14px;padding:10px 12px;font-weight:800;font-size:13px;color:#475569;cursor:pointer}
.setting-check input{width:16px;height:16px}
.notes-row td{border-top:0!important;background:#fafafa}
.supplier-view{border:2px solid rgba(37,99,235,.18)}
.import-help{border:1px dashed rgba(37,99,235,.28);background:#f8fbff;border-radius:14px;padding:10px 12px;color:#475569;font-size:13px}
.import-uploader{background:linear-gradient(135deg,#ffffff,#f8fbff);border:1px solid rgba(15,23,42,.08);border-radius:18px;padding:14px}
.import-preview-card{border:2px solid rgba(16,185,129,.22);box-shadow:0 18px 45px rgba(15,23,42,.08)}
.import-stat{border:1px solid rgba(15,23,42,.08);background:#fff;border-radius:16px;padding:12px 14px;min-height:78px}
.import-stat span{display:block;text-transform:uppercase;font-size:11px;font-weight:900;color:#64748b;letter-spacing:.06em}
.import-stat strong{display:block;font-size:26px;line-height:1.2;color:#0f172a}
.import-stat.create{background:#f0fdf4;border-color:rgba(34,197,94,.22)}
.import-stat.update{background:#eff6ff;border-color:rgba(37,99,235,.22)}
.import-stat.skip{background:#f8fafc;border-color:rgba(100,116,139,.20)}
.import-stat.error{background:#fef2f2;border-color:rgba(239,68,68,.22)}
.import-preview-table-wrap{max-height:440px;overflow:auto;border:1px solid rgba(15,23,42,.08);border-radius:16px}
.import-preview-table thead th{position:sticky;top:0;background:#f8fafc;z-index:2}
.import-row-error td{background:#fff5f5!important}
.import-row-update td{background:#f8fbff!important}


/* =========================================================
   SUPPLIERS COMPACT TOP + FROZEN LIST HEADER
   ========================================================= */
.hero-band{
    padding:12px 16px!important;
    margin-bottom:10px!important;
}
.hero-title{
    font-size:1.35rem!important;
    line-height:1.15!important;
    margin:2px 0!important;
}
.hero-subtitle{
    font-size:.82rem!important;
    line-height:1.25!important;
    margin-top:2px!important;
}
.page-eyebrow{
    font-size:.72rem!important;
    letter-spacing:.08em!important;
}
.supplier-hero-actions .btn,
.hero-band .btn{
    padding:6px 10px!important;
    font-size:.8rem!important;
    border-radius:10px!important;
}
.hero-band .row.g-4{
    --bs-gutter-y:.5rem!important;
}
.row.g-4.mb-4{
    margin-bottom:10px!important;
    --bs-gutter-x:.75rem!important;
    --bs-gutter-y:.75rem!important;
}
.metric-card{
    padding:9px 10px!important;
    gap:8px!important;
    min-height:58px!important;
}
.metric-icon{
    width:32px!important;
    height:32px!important;
    border-radius:10px!important;
    font-size:13px!important;
}
.metric-label{
    font-size:.72rem!important;
    margin-bottom:1px!important;
}
.metric-value{
    font-size:1rem!important;
    line-height:1.05!important;
}
.small-value{
    font-size:.92rem!important;
    letter-spacing:0!important;
}
.card.panel-card{
    margin-bottom:10px!important;
    border-radius:16px!important;
}
.panel-card .card-header{
    padding:10px 12px!important;
}
.panel-card .card-header h5{
    font-size:.95rem!important;
}
.panel-card .card-body{
    padding:10px!important;
}
.form-label{
    font-size:.72rem!important;
    margin-bottom:2px!important;
    font-weight:700!important;
}
.form-control,
.form-select{
    height:32px!important;
    min-height:32px!important;
    font-size:.82rem!important;
    padding:4px 8px!important;
    border-radius:9px!important;
}
textarea.form-control{
    height:auto!important;
    min-height:48px!important;
}
.row.g-3{
    --bs-gutter-x:.65rem!important;
    --bs-gutter-y:.55rem!important;
}
.mt-3{margin-top:.55rem!important;}
.mt-4{margin-top:.75rem!important;}
.mb-4{margin-bottom:.75rem!important;}
.alert{
    padding:8px 12px!important;
    margin-bottom:10px!important;
    border-radius:12px!important;
}
.supplier-table-wrap{
    max-height:calc(100vh - 245px);
    overflow:auto;
    border-radius:0 0 16px 16px;
}
.supplier-table{
    border-collapse:separate;
    border-spacing:0;
    font-size:.84rem;
}
.supplier-table thead th{
    position:sticky;
    top:0;
    z-index:12;
    background:linear-gradient(180deg,#ffffff,#f8fafc)!important;
    color:#64748b;
    border-bottom:2px solid #e5e7eb!important;
    text-transform:uppercase;
    letter-spacing:.06em;
    font-weight:850;
    white-space:nowrap;
}
.supplier-table th,
.supplier-table td{
    padding:7px 9px!important;
    vertical-align:middle!important;
}
.supplier-table th{font-size:.72rem!important;}
.supplier-table td{font-size:.82rem!important;}
.supplier-table td strong{font-size:.86rem!important;}
.supplier-table .small{font-size:.68rem!important;line-height:1.15!important;}
.supplier-table tbody tr:hover{background:#f8fafc!important;}
.supplier-table .btn-group .btn{
    min-width:29px!important;
    padding:4px 6px!important;
    border-radius:8px!important;
}
.supplier-filter-actions{
    margin-top:-2px!important;
}

@media(min-width:1200px){
    .col-xl-4{
        position:sticky;
        top:10px;
        align-self:flex-start;
        height:fit-content;
        z-index:4;
    }
}
@media(max-width:575.98px){
    .supplier-hero-actions,
    .supplier-hero-actions .btn{
        width:100%;
        justify-content:center;
    }
    .supplier-table-wrap{
        max-height:calc(100vh - 220px);
    }
}

</style>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
