<?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);
settings_ensure_head_office($conn, $org);
$flash = settings_flash_message();
$errors = [];

if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    $stmt = $conn->prepare(
        "SELECT location_name, address_line1, address_line2, state, city, pincode, is_filing_address
         FROM work_locations
         WHERE organization_id = ?
         ORDER BY is_filing_address DESC, location_name ASC"
    );
    if ($stmt) {
        $stmt->bind_param('i', $orgId);
        $stmt->execute();
        $result = $stmt->get_result();

        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="work-locations.csv"');
        $out = fopen('php://output', 'w');
        fputcsv($out, ['Location Name', 'Address Line 1', 'Address Line 2', 'State', 'City', 'PIN Code', 'Filing Address']);
        while ($row = $result->fetch_assoc()) {
            fputcsv($out, [
                $row['location_name'],
                $row['address_line1'],
                $row['address_line2'],
                $row['state'],
                $row['city'],
                $row['pincode'],
                $row['is_filing_address'] ? 'Yes' : 'No',
            ]);
        }
        fclose($out);
        $stmt->close();
        exit();
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['location_action'] ?? '';

    if ($action === 'create') {
        $locationName = trim((string) ($_POST['location_name'] ?? ''));
        $addressLine1 = trim((string) ($_POST['address_line1'] ?? ''));
        $addressLine2 = trim((string) ($_POST['address_line2'] ?? ''));
        $state = trim((string) ($_POST['state'] ?? ''));
        $city = trim((string) ($_POST['city'] ?? ''));
        $pincode = trim((string) ($_POST['pincode'] ?? ''));
        $isFilingAddress = isset($_POST['is_filing_address']) ? 1 : 0;

        if ($locationName === '') {
            $errors[] = 'Work location name is required.';
        }
        if ($addressLine1 === '') {
            $errors[] = 'Address line 1 is required.';
        }
        if ($state === '') {
            $errors[] = 'State is required.';
        }

        if (!$errors) {
            if ($isFilingAddress) {
                $reset = $conn->prepare("UPDATE work_locations SET is_filing_address = 0 WHERE organization_id = ?");
                if ($reset) {
                    $reset->bind_param('i', $orgId);
                    $reset->execute();
                    $reset->close();
                }
            }

            $stmt = $conn->prepare(
                "INSERT INTO work_locations
                 (organization_id, location_name, address_line1, address_line2, state, city, pincode, is_filing_address)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
            );
            if ($stmt) {
                $stmt->bind_param('issssssi', $orgId, $locationName, $addressLine1, $addressLine2, $state, $city, $pincode, $isFilingAddress);
                if ($stmt->execute()) {
                    settings_set_flash('success', 'Work location saved successfully.');
                    $stmt->close();
                    header('Location: locations.php');
                    exit();
                }
                $errors[] = 'Unable to save work location. It may already exist.';
                $stmt->close();
            }
        }
    } elseif ($action === 'delete') {
        $locationId = (int) ($_POST['location_id'] ?? 0);
        if ($locationId > 0) {
            $stmt = $conn->prepare("DELETE FROM work_locations WHERE id = ? AND organization_id = ?");
            if ($stmt) {
                $stmt->bind_param('ii', $locationId, $orgId);
                $stmt->execute();
                $stmt->close();
                settings_set_flash('success', 'Work location deleted successfully.');
                header('Location: locations.php');
                exit();
            }
        }
    }
}

$locations = [];
$stmt = $conn->prepare(
    "SELECT wl.*,
        (SELECT COUNT(*) FROM employees e WHERE e.work_location = wl.location_name AND e.is_deleted = 0) AS employee_count
     FROM work_locations wl
     WHERE wl.organization_id = ?
     ORDER BY wl.is_filing_address DESC, wl.location_name ASC"
);
if ($stmt) {
    $stmt->bind_param('i', $orgId);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $locations[] = $row;
    }
    $stmt->close();
}

$states = settings_get_states_for_country($conn, $org['business_location'] ?: 'India');
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Work Locations | 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">
  <link rel="stylesheet" href="locations.css">
</head>
<body class="orgprofile-page">
  <?php settings_render_header($_SESSION['org_name'] ?? 'demo', 'dashboard.php', 'fa-map-location-dot'); ?>

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

    <section class="profile-main">
      <div class="profile-head dept-toolbar">
        <h1>Work Locations</h1>
        <div class="toolbar-actions">
          <a class="btn-export" href="locations.php?export=csv" title="Export"><i class="fa-solid fa-download"></i></a>
          <button class="btn-new" type="button" onclick="openModal()"><i class="fa-solid fa-plus"></i> Add Work Location</button>
        </div>
      </div>

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

        <?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; ?>

        <div class="locations-board">
          <?php foreach ($locations as $location): ?>
            <div class="location-panel">
              <div class="location-panel__head">
                <h3><?php echo htmlspecialchars($location['location_name']); ?></h3>
                <div class="row-actions row-actions--visible">
                  <form method="POST" class="inline-form" onsubmit="return confirm('Delete this work location?');">
                    <input type="hidden" name="location_action" value="delete">
                    <input type="hidden" name="location_id" value="<?php echo (int) $location['id']; ?>">
                    <button class="row-btn danger" type="submit" title="Delete"><i class="fa-solid fa-trash"></i></button>
                  </form>
                </div>
              </div>
              <div class="location-lines">
                <div><?php echo htmlspecialchars($location['address_line1']); ?></div>
                <?php if (!empty($location['address_line2'])): ?>
                  <div><?php echo htmlspecialchars($location['address_line2']); ?></div>
                <?php endif; ?>
                <div><?php echo htmlspecialchars(trim($location['city'] . ', ' . $location['state'] . ' ' . $location['pincode'])); ?></div>
              </div>
              <div class="location-panel__foot">
                <div class="location-employees"><i class="fa-regular fa-user"></i> <?php echo (int) $location['employee_count']; ?> Employees</div>
                <?php if ((int) $location['is_filing_address'] === 1): ?>
                  <div class="location-badge">Filing Address</div>
                <?php endif; ?>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      </div>
    </section>
  </main>

  <div class="modal-overlay" id="locationModal">
    <div class="modal">
      <h3>New Work Location</h3>
      <form method="POST">
        <input type="hidden" name="location_action" value="create">
        <div class="field-group">
          <label>Work Location Name<span class="req">*</span></label>
          <input class="modal-input" type="text" name="location_name" required>
        </div>
        <div class="field-group">
          <label>Address<span class="req">*</span></label>
          <input class="modal-input" type="text" name="address_line1" placeholder="Address Line 1" required>
          <input class="modal-input" type="text" name="address_line2" placeholder="Address Line 2">
        </div>
        <div class="grid-three">
          <div class="field-group">
            <label>State<span class="req">*</span></label>
            <select name="state" class="modal-input" required>
              <option value="">Select a state</option>
              <?php foreach ($states as $state): ?>
                <option value="<?php echo htmlspecialchars($state); ?>"><?php echo htmlspecialchars($state); ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="field-group">
            <label>City</label>
            <input class="modal-input" type="text" name="city">
          </div>
          <div class="field-group">
            <label>PIN Code</label>
            <input class="modal-input" type="text" name="pincode">
          </div>
        </div>
        <div class="field-group check-row">
          <label><input type="checkbox" name="is_filing_address" value="1"> Set as filing address</label>
        </div>
        <div class="modal-footer">
          <button class="btn-cancel" type="button" onclick="closeModal()">Cancel</button>
          <button class="save-btn" type="submit">Save</button>
        </div>
      </form>
    </div>
  </div>

  <script>
    function openModal() { document.getElementById('locationModal').classList.add('open'); }
    function closeModal() { document.getElementById('locationModal').classList.remove('open'); }
    document.getElementById('locationModal').addEventListener('click', function (event) {
      if (event.target === this) {
        closeModal();
      }
    });
  </script>
</body>
</html>
