<?php

require_once __DIR__ . '/includes/settings_helpers.php';

settings_require_auth();
settings_ensure_tables($conn);

$org = settings_get_current_org($conn);
$orgId = (int) ($org['id'] ?? 0);
$view = trim((string) ($_GET['view'] ?? 'my'));
$validViews = ['my', 'system', 'default', 'custom', 'create'];
if (!in_array($view, $validViews, true)) {
    $view = 'my';
}

$errors = [];
$flash = settings_flash_message();
$services = settings_default_connection_services();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['connection_action'] ?? '') === 'create') {
    $serviceCode = trim((string) ($_POST['service_code'] ?? ''));
    $serviceName = trim((string) ($_POST['service_name'] ?? ''));
    $serviceType = trim((string) ($_POST['service_type'] ?? 'default'));
    $connectionName = trim((string) ($_POST['connection_name'] ?? ''));
    $scopeSummary = trim((string) ($_POST['scope_summary'] ?? ''));

    if ($serviceCode === '' || $serviceName === '') {
        $errors[] = 'Please select a service.';
    }
    if ($connectionName === '') {
        $errors[] = 'Connection name is required.';
    }

    if (!$errors && settings_add_connection($conn, $orgId, [
        'service_type' => $serviceType,
        'service_code' => $serviceCode,
        'service_name' => $serviceName,
        'connection_name' => $connectionName,
        'scope_summary' => $scopeSummary,
    ])) {
        settings_set_flash('success', 'Connection created successfully.');
        header('Location: connections.php?view=my');
        exit();
    } elseif (!$errors) {
        $errors[] = 'Unable to create connection. The connection name may already exist.';
    }
    $view = 'create';
}

$myConnections = settings_get_connections($conn, $orgId);
$systemConnections = settings_get_connections($conn, $orgId, 'system');
$customConnections = settings_get_connections($conn, $orgId, 'custom');
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Connections | Settings</title>
  <link rel="stylesheet" href="assets/fontawesome/css/all.min.css">
  <link rel="stylesheet" href="assets/font-inter.css">
  <link rel="stylesheet" href="orgprofile.css">
  <style>
    .conn-layout{display:grid;grid-template-columns:260px 1fr;gap:18px;}
    .conn-nav,.conn-panel{background:#fff;border:1px solid var(--border);border-radius:18px;box-shadow:var(--shadow);}
    .conn-nav{padding:18px;}
    .conn-nav a{display:block;padding:12px 14px;border-radius:12px;text-decoration:none;color:#334155;font-weight:700;margin-bottom:8px;}
    .conn-nav a.active{background:#eff6ff;color:#2563eb;}
    .conn-panel{padding:22px;}
    .conn-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:16px;}
    .service-card{padding:18px;border:1px solid var(--border);border-radius:16px;background:#fcfcff;}
    .service-card h3{margin:10px 0 4px;font-size:18px;}
    .service-card p{margin:0;color:#64748b;font-size:14px;}
    .empty-box{padding:72px 20px;text-align:center;color:#64748b;}
    .list-table{width:100%;border-collapse:collapse;}
    .list-table th,.list-table td{padding:14px 0;border-top:1px solid var(--border);text-align:left;}
    .form-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px;}
    .form-grid .full{grid-column:1 / -1;}
    .form-grid input,.form-grid textarea,.form-grid select{width:100%;border:1px solid var(--border);border-radius:10px;padding:11px 12px;font-size:14px;}
    .form-grid textarea{min-height:96px;resize:vertical;}
    .ghost-btn{display:inline-flex;align-items:center;justify-content:center;padding:10px 16px;border-radius:10px;border:1px solid var(--border);background:#fff;color:#334155;text-decoration:none;font-weight:700;}
    @media (max-width: 1024px){
      .conn-layout{grid-template-columns:1fr;}
      .conn-grid{grid-template-columns:repeat(2,minmax(0,1fr));}
    }
  </style>
</head>
<body class="orgprofile-page">
  <?php settings_render_header($_SESSION['org_name'] ?? 'demo', 'dashboard.php', 'fa-folder-open'); ?>

  <main class="profile-layout">
    <?php settings_render_sidebar('connections'); ?>

    <section class="profile-main">
      <div class="profile-head">
        <h1>Connections</h1>
        <a class="save-btn" href="connections.php?view=create">+ New Connection</a>
      </div>

      <div class="conn-layout">
        <nav class="conn-nav">
          <a class="<?php echo $view === 'my' ? 'active' : ''; ?>" href="connections.php?view=my">My Connections</a>
          <a class="<?php echo $view === 'system' ? 'active' : ''; ?>" href="connections.php?view=system">System Connections</a>
          <a class="<?php echo $view === 'default' ? 'active' : ''; ?>" href="connections.php?view=default">Default Services</a>
          <a class="<?php echo $view === 'custom' ? 'active' : ''; ?>" href="connections.php?view=custom">Custom Services</a>
        </nav>

        <div class="conn-panel">
          <?php if (!empty($flash['message'])): ?>
            <div class="alert-ok"><?php echo htmlspecialchars($flash['message']); ?></div>
          <?php endif; ?>

          <?php if ($view === 'my'): ?>
            <?php if ($myConnections): ?>
              <table class="list-table">
                <thead>
                  <tr>
                    <th>Connection Name</th>
                    <th>Service</th>
                    <th>Status</th>
                    <th>Created</th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($myConnections as $connection): ?>
                    <tr>
                      <td><?php echo htmlspecialchars($connection['connection_name']); ?></td>
                      <td><?php echo htmlspecialchars($connection['service_name']); ?></td>
                      <td><?php echo htmlspecialchars(strtoupper((string) $connection['status'])); ?></td>
                      <td><?php echo htmlspecialchars((string) $connection['created_at']); ?></td>
                    </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            <?php else: ?>
              <div class="empty-box">
                <h2>You don't have any connections yet</h2>
                <p>Use connections to connect Zoho Payroll with other applications and authenticated services.</p>
              </div>
            <?php endif; ?>
          <?php elseif ($view === 'system'): ?>
            <?php if ($systemConnections): ?>
              <table class="list-table">
                <thead>
                  <tr>
                    <th>Connection Name</th>
                    <th>Service</th>
                    <th>Status</th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($systemConnections as $connection): ?>
                    <tr>
                      <td><?php echo htmlspecialchars($connection['connection_name']); ?></td>
                      <td><?php echo htmlspecialchars($connection['service_name']); ?></td>
                      <td><?php echo htmlspecialchars(strtoupper((string) $connection['status'])); ?></td>
                    </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            <?php else: ?>
              <div class="empty-box">
                <h2>You don't have any system connections yet</h2>
                <p>When you execute a built-in Zoho integration task, system connections will be listed here.</p>
              </div>
            <?php endif; ?>
          <?php elseif ($view === 'default'): ?>
            <div class="conn-grid">
              <?php foreach ($services as $service): ?>
                <div class="service-card">
                  <div><i class="fa-solid fa-plug-circle-bolt"></i></div>
                  <h3><?php echo htmlspecialchars($service['name']); ?></h3>
                  <p>Not used</p>
                </div>
              <?php endforeach; ?>
            </div>
          <?php elseif ($view === 'custom'): ?>
            <?php if ($customConnections): ?>
              <table class="list-table">
                <thead>
                  <tr>
                    <th>Connection Name</th>
                    <th>Service</th>
                    <th>Scopes</th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($customConnections as $connection): ?>
                    <tr>
                      <td><?php echo htmlspecialchars($connection['connection_name']); ?></td>
                      <td><?php echo htmlspecialchars($connection['service_name']); ?></td>
                      <td><?php echo htmlspecialchars((string) $connection['scope_summary']); ?></td>
                    </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            <?php else: ?>
              <div class="empty-box">
                <h2>You haven't created any services yet</h2>
                <p>Create custom services here and use them later in developer workflows.</p>
              </div>
            <?php endif; ?>
          <?php else: ?>
            <?php if ($errors): ?>
              <div class="alert-err">
                <div class="alert-err-title">Please fix the following:</div>
                <ul>
                  <?php foreach ($errors as $error): ?>
                    <li><?php echo htmlspecialchars($error); ?></li>
                  <?php endforeach; ?>
                </ul>
              </div>
            <?php endif; ?>
            <form method="POST">
              <input type="hidden" name="connection_action" value="create">
              <div class="form-grid">
                <div>
                  <label>Service</label>
                  <select name="service_code" required>
                    <option value="">Select service</option>
                    <?php foreach ($services as $service): ?>
                      <option value="<?php echo htmlspecialchars($service['code']); ?>"><?php echo htmlspecialchars($service['name']); ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div>
                  <label>Connection Name</label>
                  <input type="text" name="connection_name" required>
                </div>
                <div>
                  <label>Service Type</label>
                  <select name="service_type">
                    <option value="default">Default</option>
                    <option value="custom">Custom</option>
                    <option value="system">System</option>
                  </select>
                </div>
                <div>
                  <label>Service Name</label>
                  <input type="text" name="service_name" required>
                </div>
                <div class="full">
                  <label>Scopes / Notes</label>
                  <textarea name="scope_summary" placeholder="Example: read employees, write analytics reports"></textarea>
                </div>
              </div>
              <div class="action-row" style="display:flex;gap:12px;margin-top:18px;">
                <button class="save-btn" type="submit">Create And Connect</button>
                <a class="ghost-btn" href="connections.php?view=my">Cancel</a>
              </div>
            </form>
          <?php endif; ?>
        </div>
      </div>
    </section>
  </main>
</body>
</html>
