<?php
declare(strict_types=1);
ini_set('display_errors', '0');

require_once __DIR__ . '/../includes/console_shell.php';
require_login();

$pageLink = 'organization/company-information.php';
$acl = require_acl('can_view', $pageLink);
$errors = [];
$flash = $_SESSION['flash_company_information'] ?? null;
unset($_SESSION['flash_company_information']);

function ci_stmt(mysqli $con, string $sql): mysqli_stmt
{
    $stmt = $con->prepare($sql);
    if (!$stmt) {
        throw new RuntimeException('Unable to prepare company information query.');
    }
    return $stmt;
}

function ci_columns(mysqli $con, string $table): array
{
    $safeTable = preg_replace('/[^A-Za-z0-9_]/', '', $table);
    $columns = [];
    $result = $con->query('SHOW COLUMNS FROM `' . $safeTable . '`');
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $columns[] = (string)$row['Field'];
        }
        $result->free();
    }
    return $columns;
}

function ci_has_column(mysqli $con, string $table, string $column): bool
{
    return in_array($column, ci_columns($con, $table), true);
}

function ci_ensure_schema(mysqli $con): void
{
    if (!ci_has_column($con, 'jos_app_company', 'image')) {
        $con->query("ALTER TABLE jos_app_company ADD COLUMN image varchar(500) NOT NULL DEFAULT '' AFTER logo");
    }
    if (!ci_has_column($con, 'jos_app_company', 'name_marathi')) {
        $con->query("ALTER TABLE jos_app_company ADD COLUMN name_marathi varchar(255) NOT NULL DEFAULT '' AFTER name");
    }
    if (!ci_has_column($con, 'jos_app_company', 'address_marathi')) {
        $con->query("ALTER TABLE jos_app_company ADD COLUMN address_marathi text NULL AFTER address");
    }
    if (!ci_has_column($con, 'jos_app_company', 'status')) {
        $con->query("ALTER TABLE jos_app_company ADD COLUMN status tinyint(1) NOT NULL DEFAULT 1 AFTER gstno");
    }
    if (!ci_has_column($con, 'jos_app_company', 'orderby')) {
        $con->query("ALTER TABLE jos_app_company ADD COLUMN orderby int(11) NOT NULL DEFAULT 0 AFTER status");
    }
}

function ci_options(mysqli $con, string $sql): array
{
    $rows = [];
    $stmt = ci_stmt($con, $sql);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }
    $stmt->close();
    return $rows;
}

function ci_text(array $row, string $key, string $default = ''): string
{
    return array_key_exists($key, $row) && $row[$key] !== null ? (string)$row[$key] : $default;
}

function ci_int(array $row, string $key, int $default = 0): int
{
    return array_key_exists($key, $row) && $row[$key] !== null ? (int)$row[$key] : $default;
}

function ci_company_exists(mysqli $con, int $id): bool
{
    if ($id <= 0) {
        return false;
    }
    $stmt = ci_stmt($con, 'SELECT id FROM jos_app_company WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $exists = (bool)$stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $exists;
}

function ci_fetch_company(mysqli $con, int $id): ?array
{
    if ($id <= 0) {
        return null;
    }
    $stmt = ci_stmt($con, 'SELECT * FROM jos_app_company WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc() ?: null;
    $stmt->close();
    return $row;
}

function ci_duplicate_name(mysqli $con, string $name, int $excludeId = 0): bool
{
    if ($excludeId > 0) {
        $stmt = ci_stmt($con, 'SELECT id FROM jos_app_company WHERE LOWER(name)=LOWER(?) AND id<>? LIMIT 1');
        $stmt->bind_param('si', $name, $excludeId);
    } else {
        $stmt = ci_stmt($con, 'SELECT id FROM jos_app_company WHERE LOWER(name)=LOWER(?) LIMIT 1');
        $stmt->bind_param('s', $name);
    }
    $stmt->execute();
    $exists = (bool)$stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $exists;
}

function ci_clean_path(string $path): string
{
    $path = trim(str_replace('\\', '/', $path));
    $path = ltrim($path, '/');
    if ($path === '' || str_contains($path, '..') || preg_match('/[\x00-\x1F]/', $path)) {
        return '';
    }
    return $path;
}

function ci_public_image_src(string $path): string
{
    $clean = ci_clean_path($path);
    if ($clean === '') {
        return '';
    }
    if (preg_match('#^https?://#i', $clean)) {
        return $clean;
    }
    return '/' . $clean;
}

function ci_upload_image(string $field, string $existing, array &$errors): string
{
    if (empty($_FILES[$field]) || !is_array($_FILES[$field])) {
        return $existing;
    }
    $file = $_FILES[$field];
    $error = (int)($file['error'] ?? UPLOAD_ERR_NO_FILE);
    if ($error === UPLOAD_ERR_NO_FILE) {
        return $existing;
    }
    if ($error !== UPLOAD_ERR_OK) {
        $errors[] = ucfirst(str_replace('_', ' ', $field)) . ' upload failed.';
        return $existing;
    }
    $size = (int)($file['size'] ?? 0);
    if ($size <= 0 || $size > 2 * 1024 * 1024) {
        $errors[] = ucfirst(str_replace('_', ' ', $field)) . ' must be a JPEG, PNG, or WebP image up to 2 MB.';
        return $existing;
    }
    $tmp = (string)($file['tmp_name'] ?? '');
    if ($tmp === '' || !is_uploaded_file($tmp)) {
        $errors[] = ucfirst(str_replace('_', ' ', $field)) . ' upload was not accepted.';
        return $existing;
    }
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = (string)$finfo->file($tmp);
    $extensions = [
        'image/jpeg' => 'jpg',
        'image/png' => 'png',
        'image/webp' => 'webp',
    ];
    if (!isset($extensions[$mime])) {
        $errors[] = ucfirst(str_replace('_', ' ', $field)) . ' must be a JPEG, PNG, or WebP image.';
        return $existing;
    }
    $uploadDir = dirname(__DIR__) . '/storage/company';
    if (!is_dir($uploadDir) && !mkdir($uploadDir, 0755, true)) {
        $errors[] = 'Unable to prepare company upload directory.';
        return $existing;
    }
    $filename = $field . '_' . date('YmdHis') . '_' . bin2hex(random_bytes(8)) . '.' . $extensions[$mime];
    $target = $uploadDir . '/' . $filename;
    if (!move_uploaded_file($tmp, $target)) {
        $errors[] = ucfirst(str_replace('_', ' ', $field)) . ' could not be saved.';
        return $existing;
    }
    return 'storage/company/' . $filename;
}

function ci_validate_gst(string $value, array &$errors): void
{
    if ($value !== '' && !preg_match('/^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z][1-9A-Z]Z[0-9A-Z]$/', strtoupper($value))) {
        $errors[] = 'GST number format is invalid.';
    }
}

function ci_insert_history(mysqli $con, int $companyId): void
{
    if (!ci_columns($con, 'jos_app_companyinfo_editlog')) {
        return;
    }
    $company = ci_fetch_company($con, $companyId);
    if (!$company) {
        return;
    }
    $userId = (int)(current_user()['id'] ?? 0);
    $fields = [
        'uid' => $companyId,
        'date' => null,
        'store_name' => ci_text($company, 'name'),
        'image' => ci_text($company, 'image'),
        'password' => '',
        'address' => ci_text($company, 'address'),
        'contactno' => ci_text($company, 'contactno'),
        'logo' => ci_text($company, 'logo'),
        'website' => ci_text($company, 'website'),
        'email' => ci_text($company, 'email'),
        'gstno' => ci_text($company, 'gstno'),
        'staffapp' => 0,
        'locationsynctime' => 0,
        'employee_count' => 0,
        'employee_face_count' => 1,
        'erp_empid' => 0,
        'payroll' => '',
        'modify_by' => (string)$userId,
        'modify_date' => date('Y-m-d H:i:s'),
        'live_tracking_count' => ci_int($company, 'live_tracking_count'),
        'addpayroll' => 0,
        'branchlocation' => 0,
        'visitorlog' => 0,
        'vehiclelog' => 0,
        'expenselog' => 0,
        'attendreport' => 0,
        'attend' => 0,
        'leavemanage' => 0,
        'leadmanage' => 0,
        'subbranch' => 0,
        'salsubbranch' => 0,
        'isGeofence' => 0,
        'isLoginGeofence' => 0,
        'isLogoutGeofence' => 0,
        'stamp' => '',
    ];
    $columns = ci_columns($con, 'jos_app_companyinfo_editlog');
    $insertFields = [];
    $placeholders = [];
    $types = '';
    $params = [];
    foreach ($fields as $field => $value) {
        if (!in_array($field, $columns, true)) {
            continue;
        }
        $insertFields[] = $field;
        if ($field === 'date') {
            $placeholders[] = 'NOW()';
            continue;
        }
        $placeholders[] = '?';
        if (is_int($value)) {
            $types .= 'i';
            $params[] = $value;
        } else {
            $types .= 's';
            $params[] = (string)$value;
        }
    }
    if (!$insertFields) {
        return;
    }
    $stmt = ci_stmt($con, 'INSERT INTO jos_app_companyinfo_editlog (`' . implode('`,`', $insertFields) . '`) VALUES (' . implode(',', $placeholders) . ')');
    if ($types !== '') {
        $stmt->bind_param($types, ...$params);
    }
    $stmt->execute();
    $stmt->close();
}

function ci_save_company(mysqli $con, int $id, array $data): int
{
    $columns = ci_columns($con, 'jos_app_company');
    $spec = [
        'userid' => 'i',
        'name' => 's',
        'name_marathi' => 's',
        'address' => 's',
        'address_marathi' => 's',
        'contactno' => 's',
        'logo' => 's',
        'image' => 's',
        'website' => 's',
        'email' => 's',
        'gstno' => 's',
        'live_tracking_count' => 'i',
        'status' => 'i',
        'orderby' => 'i',
    ];
    $fields = [];
    $types = '';
    $params = [];
    foreach ($spec as $field => $type) {
        if (!in_array($field, $columns, true)) {
            continue;
        }
        $fields[] = $field;
        $types .= $type;
        $params[] = $type === 'i' ? (int)$data[$field] : (string)$data[$field];
    }
    if ($id > 0) {
        $sets = array_map(static fn($field) => '`' . $field . '`=?', $fields);
        $stmt = ci_stmt($con, 'UPDATE jos_app_company SET ' . implode(',', $sets) . ' WHERE id=?');
        $types .= 'i';
        $params[] = $id;
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $stmt->close();
        return $id;
    }
    $stmt = ci_stmt($con, 'INSERT INTO jos_app_company (`' . implode('`,`', $fields) . '`) VALUES (' . implode(',', array_fill(0, count($fields), '?')) . ')');
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $savedId = (int)$con->insert_id;
    $stmt->close();
    return $savedId;
}

function ci_update_status(mysqli $con, int $id, int $status): void
{
    $stmt = ci_stmt($con, 'UPDATE jos_app_company SET status=? WHERE id=?');
    $stmt->bind_param('ii', $status, $id);
    $stmt->execute();
    $stmt->close();
}

ci_ensure_schema($con);

$mode = (string)($_GET['mode'] ?? '');
$isForm = $mode === 'add';
$editId = isset($_GET['edit']) ? max(0, (int)$_GET['edit']) : 0;
$viewId = isset($_GET['view']) ? max(0, (int)$_GET['view']) : 0;
$viewRow = null;

if ($isForm && empty($acl['can_add'])) {
    http_response_code(403);
    exit('Access denied.');
}

$editRow = [
    'id' => 0,
    'userid' => (int)(current_user()['id'] ?? 0),
    'name' => '',
    'name_marathi' => '',
    'address' => '',
    'address_marathi' => '',
    'contactno' => '',
    'logo' => '',
    'image' => '',
    'website' => '',
    'email' => '',
    'gstno' => '',
    'live_tracking_count' => 0,
    'status' => 1,
    'orderby' => 0,
];

if ($editId > 0) {
    if (empty($acl['can_edit'])) {
        http_response_code(403);
        exit('Access denied.');
    }
    $isForm = true;
    $editRow = ci_fetch_company($con, $editId) ?: [];
    if (!$editRow) {
        $_SESSION['flash_company_information'] = 'Company record was not found.';
        redirect('/organization/company-information.php');
    }
}

if ($viewId > 0) {
    $viewRow = ci_fetch_company($con, $viewId);
    if (!$viewRow) {
        $_SESSION['flash_company_information'] = 'Company record was not found.';
        redirect('/organization/company-information.php');
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');
    if (!verify_csrf($_POST['_csrf'] ?? null)) {
        $errors[] = 'Security token expired. Please refresh and try again.';
    } elseif ($action === 'save') {
        $id = max(0, (int)($_POST['id'] ?? 0));
        if ($id > 0 && empty($acl['can_edit'])) {
            $errors[] = 'You do not have permission to edit company information.';
        }
        if ($id === 0 && empty($acl['can_add'])) {
            $errors[] = 'You do not have permission to add company information.';
        }
        if ($id > 0 && !ci_company_exists($con, $id)) {
            $errors[] = 'Company record was not found.';
        }
        $existing = $id > 0 ? ci_fetch_company($con, $id) : $editRow;
        $name = trim((string)($_POST['name'] ?? ''));
        $nameMarathi = trim((string)($_POST['name_marathi'] ?? ''));
        $address = trim((string)($_POST['address'] ?? ''));
        $addressMarathi = trim((string)($_POST['address_marathi'] ?? ''));
        $contact = trim((string)($_POST['contactno'] ?? ''));
        $website = trim((string)($_POST['website'] ?? ''));
        $email = trim((string)($_POST['email'] ?? ''));
        $gst = strtoupper(trim((string)($_POST['gstno'] ?? '')));
        $liveTracking = ci_int($existing ?: [], 'live_tracking_count', 0);
        $status = ci_int($existing ?: [], 'status', 1);
        $order = ci_int($existing ?: [], 'orderby', 0);

        if ($name === '') {
            $errors[] = 'Organisation name is required.';
        } elseif (strlen($name) > 255) {
            $errors[] = 'Organisation name must be 255 characters or fewer.';
        } elseif (ci_duplicate_name($con, $name, $id)) {
            $errors[] = 'Organisation name already exists.';
        }
        if ($address === '') {
            $errors[] = 'Company address is required.';
        }
        if ($contact === '') {
            $errors[] = 'Contact number is required.';
        } elseif (!preg_match('/^[0-9+\-\s()]{6,20}$/', $contact)) {
            $errors[] = 'Contact number format is invalid.';
        }
        if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = 'Email address format is invalid.';
        }
        if ($website !== '' && !filter_var($website, FILTER_VALIDATE_URL)) {
            $errors[] = 'Website URL format is invalid.';
        }
        ci_validate_gst($gst, $errors);

        $logo = ci_upload_image('logo', ci_text($existing ?: [], 'logo'), $errors);
        $image = ci_upload_image('image', ci_text($existing ?: [], 'image'), $errors);

        $editRow = [
            'id' => $id,
            'userid' => (int)(current_user()['id'] ?? 0),
            'name' => $name,
            'name_marathi' => $nameMarathi,
            'address' => $address,
            'address_marathi' => $addressMarathi,
            'contactno' => $contact,
            'logo' => $logo,
            'image' => $image,
            'website' => $website,
            'email' => $email,
            'gstno' => $gst,
            'live_tracking_count' => $liveTracking,
            'status' => $status,
            'orderby' => $order,
        ];

        if (!$errors) {
            try {
                $con->begin_transaction();
                $savedId = ci_save_company($con, $id, $editRow);
                ci_insert_history($con, $savedId);
                $con->commit();
                $_SESSION['flash_company_information'] = $id > 0 ? 'Company Information updated successfully.' : 'Company Information added successfully.';
                redirect('/organization/company-information.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to save company information. No changes were committed.';
            }
        }
        $isForm = true;
    } elseif ($action === 'status') {
        $id = max(0, (int)($_POST['id'] ?? 0));
        $targetStatus = (int)($_POST['status'] ?? 0) === 1 ? 1 : 0;
        if (empty($acl['can_delete'])) {
            $errors[] = 'You do not have permission to activate or deactivate company records.';
        } elseif (!ci_company_exists($con, $id)) {
            $errors[] = 'Company record was not found.';
        } else {
            try {
                ci_update_status($con, $id, $targetStatus);
                ci_insert_history($con, $id);
                $_SESSION['flash_company_information'] = $targetStatus === 1 ? 'Company Information activated successfully.' : 'Company Information deactivated successfully.';
                redirect('/organization/company-information.php');
            } catch (Throwable $e) {
                $errors[] = 'Unable to update company status.';
            }
        }
    } elseif ($action === 'delete') {
        $id = max(0, (int)($_POST['id'] ?? 0));
        if (empty($acl['can_delete'])) {
            $errors[] = 'You do not have permission to delete company records.';
        } elseif (!ci_company_exists($con, $id)) {
            $errors[] = 'Company record was not found.';
        } else {
            try {
                $stmt = ci_stmt($con, 'DELETE FROM jos_app_company WHERE id=?');
                $stmt->bind_param('i', $id);
                $stmt->execute();
                $stmt->close();
                $_SESSION['flash_company_information'] = 'Company Information deleted successfully.';
                redirect('/organization/company-information.php');
            } catch (Throwable $e) {
                $errors[] = 'Unable to delete company information.';
            }
        }
    }
}

$filterQ = trim((string)($_GET['q'] ?? ''));
$filterStatus = isset($_GET['status']) && $_GET['status'] !== '' ? (int)$_GET['status'] : -1;
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 15;
$where = [];
$types = '';
$params = [];
if ($filterQ !== '') {
    $like = '%' . $filterQ . '%';
    $where[] = '(name LIKE ? OR address LIKE ? OR contactno LIKE ? OR website LIKE ? OR email LIKE ? OR gstno LIKE ?)';
    $types .= 'ssssss';
    array_push($params, $like, $like, $like, $like, $like, $like);
}
if ($filterStatus === 0 || $filterStatus === 1) {
    $where[] = 'status=?';
    $types .= 'i';
    $params[] = $filterStatus;
}
$whereSql = $where ? implode(' AND ', $where) : '1=1';

$countStmt = ci_stmt($con, 'SELECT COUNT(*) AS total FROM jos_app_company WHERE ' . $whereSql);
if ($types !== '') {
    $countStmt->bind_param($types, ...$params);
}
$countStmt->execute();
$totalRows = (int)($countStmt->get_result()->fetch_assoc()['total'] ?? 0);
$countStmt->close();
$pages = max(1, (int)ceil($totalRows / $perPage));
$page = min($page, $pages);
$offset = ($page - 1) * $perPage;

$rows = [];
$listSql = 'SELECT * FROM jos_app_company WHERE ' . $whereSql . ' ORDER BY orderby ASC,id DESC LIMIT ? OFFSET ?';
$listTypes = $types . 'ii';
$listParams = array_merge($params, [$perPage, $offset]);
$stmt = ci_stmt($con, $listSql);
$stmt->bind_param($listTypes, ...$listParams);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $rows[] = $row;
}
$stmt->close();

$value = static function (string $key, $default = '') use (&$editRow) {
    return $editRow[$key] ?? $default;
};
$input = 'mt-1 w-full rounded-lg border border-slate-200 bg-white px-3 py-2.5 text-sm text-slate-800 outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-100';
$filterInput = 'rounded-xl border border-slate-200 px-3 py-2.5 text-sm';

console_header('Company Information', $pageLink);
?>
<div class="mb-6">
  <div class="mb-2 flex items-center gap-2 text-xs font-semibold text-slate-500"><a href="/dashboard.php">Dashboard</a><i class="fa-solid fa-chevron-right text-[9px]"></i><span>D. Masters</span><i class="fa-solid fa-chevron-right text-[9px]"></i><span>Organisation Settings</span><i class="fa-solid fa-chevron-right text-[9px]"></i><span class="text-brand-600">Company Information</span></div>
  <h1 class="text-2xl font-bold text-slate-900">Company Information</h1>
  <p class="mt-1 text-sm text-slate-500">Manage organisation identity, contact details, GST details, and company logos.</p>
</div>

<?php if ($flash): ?><div class="mb-5 rounded-xl border border-emerald-100 bg-emerald-50 px-5 py-4 text-sm font-semibold text-emerald-700"><i class="fa-solid fa-circle-check mr-2"></i><?= h($flash) ?></div><?php endif; ?>
<?php if ($errors): ?><div class="mb-5 rounded-xl border border-red-100 bg-red-50 px-5 py-4 text-sm font-semibold text-red-700"><div class="font-bold">Please fix the following</div><ul class="mt-2 list-inside list-disc"><?php foreach ($errors as $error): ?><li><?= h($error) ?></li><?php endforeach; ?></ul></div><?php endif; ?>

<?php if ($viewRow): ?>
<section class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm">
  <div class="flex flex-col gap-3 border-b border-slate-100 px-5 py-4 sm:flex-row sm:items-center sm:justify-between"><div><h2 class="text-lg font-bold text-slate-800">Company Details</h2><p class="mt-1 text-sm font-medium text-slate-400"><?= h(ci_text($viewRow, 'name')) ?></p></div><a href="/organization/company-information.php" class="rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-bold text-slate-600 hover:bg-slate-50"><i class="fa-solid fa-arrow-left mr-2"></i>Back to List</a></div>
  <div class="grid gap-5 p-5 lg:grid-cols-[260px_1fr]">
    <div class="space-y-4">
      <?php foreach ([['logo', 'Company Logo'], ['image', 'APK Logo']] as $img): $src = ci_public_image_src(ci_text($viewRow, $img[0])); ?>
        <div class="rounded-xl border border-slate-100 bg-slate-50 p-4"><div class="mb-2 text-xs font-bold uppercase tracking-wide text-slate-500"><?= h($img[1]) ?></div><?php if ($src): ?><img src="<?= h($src) ?>" alt="<?= h($img[1]) ?>" class="h-28 w-full rounded-lg object-contain bg-white border border-slate-100"><?php else: ?><div class="flex h-28 items-center justify-center rounded-lg bg-white text-sm font-semibold text-slate-400">No image</div><?php endif; ?></div>
      <?php endforeach; ?>
    </div>
    <dl class="grid gap-4 md:grid-cols-2">
      <?php foreach ([['Organisation Name','name'], ['Name in Marathi','name_marathi'], ['Address','address'], ['Address in Marathi','address_marathi'], ['Contact Number','contactno'], ['Website','website'], ['Email','email'], ['GST No','gstno']] as $item): ?>
        <div class="rounded-xl border border-slate-100 p-4"><dt class="text-xs font-bold uppercase tracking-wide text-slate-400"><?= h($item[0]) ?></dt><dd class="mt-2 font-semibold text-slate-800"><?= h(ci_text($viewRow, $item[1], '-')) ?></dd></div>
      <?php endforeach; ?>
    </dl>
  </div>
</section>
<?php elseif ($isForm): ?>
<form method="post" enctype="multipart/form-data">
  <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>"><input type="hidden" name="action" value="save"><input type="hidden" name="id" value="<?= (int)$value('id') ?>">
  <section class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm">
    <div class="flex flex-col gap-3 border-b border-slate-100 px-5 py-4 sm:flex-row sm:items-center sm:justify-between"><div class="flex items-center gap-3"><span class="flex h-10 w-10 items-center justify-center rounded-xl bg-brand-50 text-brand-600"><i class="fa-solid fa-building"></i></span><div><h2 class="text-lg font-bold text-slate-800"><?= (int)$value('id') > 0 ? 'Edit Company Information' : 'New Company Information' ?></h2><p class="mt-1 text-sm font-medium text-slate-400">Fields marked with * are required.</p></div></div><a href="/organization/company-information.php" class="rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-bold text-slate-600 hover:bg-slate-50"><i class="fa-solid fa-arrow-left mr-2"></i>Back to List</a></div>
    <div class="grid gap-x-6 gap-y-5 p-5 xl:grid-cols-12">
      <div class="xl:col-span-12 text-sm font-extrabold text-red-600">Note : In organization name do not write apostrophe symbol</div>
      <label class="text-sm font-bold text-slate-700 xl:col-span-4">Organization Name *<input name="name" required maxlength="255" value="<?= h((string)$value('name')) ?>" class="<?= $input ?>" placeholder="Organization Name"></label>
      <label class="text-sm font-bold text-slate-700 xl:col-span-4">Name in Marathi<input name="name_marathi" maxlength="255" value="<?= h((string)$value('name_marathi')) ?>" class="<?= $input ?>" placeholder="Name in Marathi"></label>
      <label class="text-sm font-bold text-slate-700 xl:col-span-2">Contact Number *<input name="contactno" required maxlength="20" value="<?= h((string)$value('contactno')) ?>" class="<?= $input ?>" placeholder="Contact Number"></label>
      <label class="text-sm font-bold text-slate-700 xl:col-span-2">Email Id<input type="email" name="email" maxlength="255" value="<?= h((string)$value('email')) ?>" class="<?= $input ?>" placeholder="Email Id"></label>
      <label class="text-sm font-bold text-slate-700 xl:col-span-4">Address *<textarea name="address" required rows="5" class="<?= $input ?>" placeholder="Address"><?= h((string)$value('address')) ?></textarea></label>
      <label class="text-sm font-bold text-slate-700 xl:col-span-4">Address in Marathi<textarea name="address_marathi" rows="5" class="<?= $input ?>" placeholder="Address"><?= h((string)$value('address_marathi')) ?></textarea></label>
      <div class="space-y-5 xl:col-span-4">
        <label class="block text-sm font-bold text-slate-700">Website<input type="url" name="website" maxlength="255" value="<?= h((string)$value('website')) ?>" class="<?= $input ?>" placeholder="Website"></label>
        <label class="block text-sm font-bold text-slate-700">GST No<input name="gstno" maxlength="15" value="<?= h((string)$value('gstno')) ?>" class="<?= $input ?>" placeholder="GST No"></label>
      </div>
      <?php foreach ([['logo', 'Logo'], ['image', 'APK Logo']] as $img): $src = ci_public_image_src((string)$value($img[0])); ?>
      <div class="space-y-2 xl:col-span-4">
        <label class="text-sm font-bold text-slate-700"><?= h($img[1]) ?><input type="file" name="<?= h($img[0]) ?>" accept="image/jpeg,image/png,image/webp" class="<?= $input ?>"></label>
        <?php if ($src): ?><img src="<?= h($src) ?>" alt="<?= h($img[1]) ?>" class="h-20 w-36 rounded-lg border border-slate-100 object-contain bg-slate-50"><?php endif; ?>
      </div>
      <?php endforeach; ?>
    </div>
  </section>
  <div class="mt-5 flex justify-center gap-3"><button class="rounded-lg bg-slate-800 px-8 py-2.5 text-sm font-bold text-white shadow-sm hover:bg-slate-900">Submit</button><a href="/organization/company-information.php" class="rounded-lg border border-slate-200 bg-white px-8 py-2.5 text-sm font-bold text-slate-600 hover:bg-slate-50">Cancel</a></div>
</form>
<?php else: ?>
<section class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm">
  <div class="flex flex-col gap-3 border-b border-slate-100 px-5 py-4 sm:flex-row sm:items-center sm:justify-between"><div><h2 class="text-lg font-bold text-slate-800">Company Information List</h2><p class="mt-1 text-sm font-medium text-slate-400">Company records are ordered by latest record.</p></div><?php if (!empty($acl['can_add'])): ?><a href="?mode=add" class="inline-flex items-center justify-center gap-2 rounded-lg bg-brand-600 px-4 py-2.5 text-sm font-bold text-white shadow-sm hover:bg-brand-700"><i class="fa-solid fa-plus"></i>Add</a><?php endif; ?></div>
  <form method="get" class="grid gap-3 border-b border-slate-100 p-5 md:grid-cols-2 xl:grid-cols-5"><input name="q" value="<?= h($filterQ) ?>" class="<?= $filterInput ?>" placeholder="Search company, contact, GST"><select name="status" class="<?= $filterInput ?>"><option value="">All Status</option><option value="1" <?= $filterStatus === 1 ? 'selected' : '' ?>>Active</option><option value="0" <?= $filterStatus === 0 ? 'selected' : '' ?>>Inactive</option></select><div class="flex gap-2 xl:col-span-3"><button class="rounded-xl bg-slate-900 px-5 py-2.5 text-sm font-bold text-white"><i class="fa-solid fa-filter mr-2"></i>Filter</button><a href="/organization/company-information.php" class="rounded-xl border border-slate-200 px-5 py-2.5 text-sm font-bold text-slate-600">Clear</a></div></form>
  <div class="overflow-x-auto"><table class="w-full min-w-[1180px] text-left text-sm"><thead class="bg-slate-50 text-[10px] font-extrabold uppercase tracking-wider text-slate-600"><tr><th class="px-5 py-4">Sr No</th><th class="px-5 py-4">Organization Name</th><th class="px-5 py-4">Name in Marathi</th><th class="px-5 py-4">Address</th><th class="px-5 py-4">Address in Marathi</th><th class="px-5 py-4">Contact Number</th><th class="px-5 py-4">Logo</th><th class="px-5 py-4">APK Logo</th><th class="px-5 py-4">Website</th><th class="px-5 py-4">Email</th><th class="px-5 py-4">GST No</th><th class="px-5 py-4 text-right">Actions</th></tr></thead><tbody class="divide-y divide-slate-100">
    <?php if (!$rows): ?><tr><td colspan="12" class="px-6 py-14 text-center font-semibold text-slate-400">No company information found.</td></tr><?php endif; ?>
    <?php foreach ($rows as $index => $row): $logoSrc = ci_public_image_src(ci_text($row, 'logo')); $apkSrc = ci_public_image_src(ci_text($row, 'image')); ?>
      <tr class="align-top hover:bg-slate-50/70"><td class="px-5 py-4 font-semibold text-slate-500"><?= (($page - 1) * $perPage) + $index + 1 ?></td><td class="px-5 py-4 font-bold text-slate-800"><?= h(ci_text($row, 'name')) ?></td><td class="px-5 py-4"><?= h(ci_text($row, 'name_marathi', '-')) ?></td><td class="max-w-xs px-5 py-4 font-semibold text-slate-600"><?= h(ci_text($row, 'address', '-')) ?></td><td class="max-w-xs px-5 py-4 font-semibold text-slate-600"><?= h(ci_text($row, 'address_marathi', '-')) ?></td><td class="px-5 py-4"><?= h(ci_text($row, 'contactno', '-')) ?></td><td class="px-5 py-4"><?php if ($logoSrc): ?><img src="<?= h($logoSrc) ?>" alt="Logo" class="h-10 w-16 rounded border border-slate-100 object-contain bg-white"><?php else: ?><span class="text-slate-400">-</span><?php endif; ?></td><td class="px-5 py-4"><?php if ($apkSrc): ?><img src="<?= h($apkSrc) ?>" alt="APK Logo" class="h-10 w-16 rounded border border-slate-100 object-contain bg-white"><?php else: ?><span class="text-slate-400">-</span><?php endif; ?></td><td class="px-5 py-4"><?= ci_text($row, 'website') !== '' ? '<a class="font-semibold text-brand-600" href="' . h(ci_text($row, 'website')) . '" target="_blank" rel="noopener">Website</a>' : '-' ?></td><td class="px-5 py-4"><?= h(ci_text($row, 'email', '-')) ?></td><td class="px-5 py-4"><?= h(ci_text($row, 'gstno', '-')) ?></td><td class="px-5 py-4"><div class="flex justify-end gap-2"><?php if (!empty($acl['can_edit'])): ?><a href="?edit=<?= (int)$row['id'] ?>" class="rounded-lg border border-slate-200 px-3 py-2 text-slate-600 hover:bg-brand-50 hover:text-brand-600" title="Edit"><i class="fa-solid fa-pen-to-square"></i></a><?php endif; ?><a href="?view=<?= (int)$row['id'] ?>" class="rounded-lg border border-slate-200 px-3 py-2 text-slate-600 hover:bg-brand-50 hover:text-brand-600" title="View"><i class="fa-solid fa-eye"></i></a><?php if (!empty($acl['can_delete'])): ?><form method="post" class="inline" onsubmit="return confirm('<?= ci_int($row, 'status', 1) ? 'Deactivate' : 'Activate' ?> this company?');"><input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>"><input type="hidden" name="action" value="status"><input type="hidden" name="id" value="<?= (int)$row['id'] ?>"><input type="hidden" name="status" value="<?= ci_int($row, 'status', 1) ? 0 : 1 ?>"><button type="submit" class="rounded-lg border border-slate-200 px-3 py-2 <?= ci_int($row, 'status', 1) ? 'text-amber-600 hover:bg-amber-50' : 'text-emerald-600 hover:bg-emerald-50' ?>" title="<?= ci_int($row, 'status', 1) ? 'Deactivate' : 'Activate' ?>"><i class="fa-solid <?= ci_int($row, 'status', 1) ? 'fa-ban' : 'fa-check' ?>"></i></button></form><form method="post" class="inline" onsubmit="return confirm('Delete this company permanently?');"><input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?= (int)$row['id'] ?>"><button type="submit" class="rounded-lg border border-slate-200 px-3 py-2 text-red-600 hover:bg-red-50" title="Delete"><i class="fa-solid fa-trash"></i></button></form><?php endif; ?></div></td></tr>
    <?php endforeach; ?>
  </tbody></table></div>
  <?php if ($totalRows > $perPage): ?><div class="flex items-center justify-between border-t border-slate-100 px-5 py-4 text-sm"><span class="font-medium text-slate-500"><?= $totalRows ?> companies</span><div class="flex gap-2"><?php $base = ['q' => $filterQ, 'status' => $filterStatus >= 0 ? $filterStatus : '']; if ($page > 1): ?><a class="rounded-lg border border-slate-200 px-4 py-2 font-semibold" href="?<?= h(http_build_query($base + ['page' => $page - 1])) ?>">Previous</a><?php endif; ?><?php if ($page < $pages): ?><a class="rounded-lg border border-slate-200 px-4 py-2 font-semibold" href="?<?= h(http_build_query($base + ['page' => $page + 1])) ?>">Next</a><?php endif; ?></div></div><?php endif; ?>
</section>
<?php endif; ?>
<?php console_footer(); ?>
