<?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);
$orgCode = $org['org_id'] ?: (string) $orgId;
$settings = settings_get_org_settings($conn, $orgId);
$states = settings_get_states_for_country($conn, $org['business_location'] ?: 'India');
$flash = settings_flash_message();
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $organisationName = trim((string) ($_POST['organisation_name'] ?? ''));
    $businessLocation = trim((string) ($_POST['business_location'] ?? 'India'));
    $industry = trim((string) ($_POST['industry'] ?? 'Technology'));
    $dateFormat = trim((string) ($_POST['date_format'] ?? 'dd/MM/yyyy'));
    $fieldSeparator = trim((string) ($_POST['field_separator'] ?? '/'));
    $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'] ?? ''));
    $primaryContactName = trim((string) ($_POST['primary_contact_name'] ?? ''));
    $primaryContactEmail = trim((string) ($_POST['primary_contact_email'] ?? ''));
    $senderEmail = trim((string) ($_POST['sender_email'] ?? 'message-service@mail.zohopayroll.in'));

    if ($organisationName === '') {
        $errors[] = 'Organisation name is required.';
    }
    if ($addressLine1 === '') {
        $errors[] = 'Organisation address line 1 is required.';
    }
    if ($state === '') {
        $errors[] = 'State is required.';
    }
    if ($primaryContactEmail !== '' && !filter_var($primaryContactEmail, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Primary contact email address is invalid.';
    }
    if ($senderEmail !== '' && !filter_var($senderEmail, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Sender email address is invalid.';
    }

    if (!$errors) {
        $update = $conn->prepare(
            "UPDATE organizations
             SET organisation_name = ?, business_location = ?, industry = ?, address_line1 = ?, address_line2 = ?, state = ?, city = ?, pincode = ?
             WHERE id = ?"
        );

        if ($update) {
            $update->bind_param(
                'ssssssssi',
                $organisationName,
                $businessLocation,
                $industry,
                $addressLine1,
                $addressLine2,
                $state,
                $city,
                $pincode,
                $orgId
            );
            $update->execute();
            $update->close();
        }

        settings_upsert_org_settings($conn, $orgId, [
            'date_format' => $dateFormat,
            'field_separator' => $fieldSeparator,
            'primary_contact_name' => $primaryContactName,
            'primary_contact_email' => $primaryContactEmail,
            'sender_email' => $senderEmail,
            'logo_path' => $settings['logo_path'] ?? null,
        ]);

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

        $headOffice = $conn->prepare(
            "INSERT INTO work_locations
            (organization_id, location_name, address_line1, address_line2, state, city, pincode, is_filing_address)
            VALUES (?, 'Head Office', ?, ?, ?, ?, ?, 1)
            ON DUPLICATE KEY UPDATE
            address_line1 = VALUES(address_line1),
            address_line2 = VALUES(address_line2),
            state = VALUES(state),
            city = VALUES(city),
            pincode = VALUES(pincode),
            is_filing_address = 1"
        );
        if ($headOffice) {
            $headOffice->bind_param('isssss', $orgId, $addressLine1, $addressLine2, $state, $city, $pincode);
            $headOffice->execute();
            $headOffice->close();
        }

        $_SESSION['org_name'] = $organisationName;
        settings_set_flash('success', 'Organisation profile updated successfully.');
        header('Location: orgprofile.php');
        exit();
    }

    $org = array_merge($org, [
        'organisation_name' => $organisationName,
        'business_location' => $businessLocation,
        'industry' => $industry,
        'address_line1' => $addressLine1,
        'address_line2' => $addressLine2,
        'state' => $state,
        'city' => $city,
        'pincode' => $pincode,
    ]);
    $settings = array_merge($settings, [
        'date_format' => $dateFormat,
        'field_separator' => $fieldSeparator,
        'primary_contact_name' => $primaryContactName,
        'primary_contact_email' => $primaryContactEmail,
        'sender_email' => $senderEmail,
    ]);
    $states = settings_get_states_for_country($conn, $businessLocation);
}

$filingAddress = null;
$filingStmt = $conn->prepare(
    "SELECT location_name, address_line1, address_line2, city, state, pincode
     FROM work_locations
     WHERE organization_id = ? AND is_filing_address = 1
     ORDER BY id DESC
     LIMIT 1"
);
if ($filingStmt) {
    $filingStmt->bind_param('i', $orgId);
    $filingStmt->execute();
    $filingResult = $filingStmt->get_result();
    $filingAddress = $filingResult ? $filingResult->fetch_assoc() : null;
    $filingStmt->close();
}

if (!$filingAddress) {
    settings_ensure_head_office($conn, $org);
    $filingStmt = $conn->prepare(
        "SELECT location_name, address_line1, address_line2, city, state, pincode
         FROM work_locations
         WHERE organization_id = ? AND is_filing_address = 1
         ORDER BY id DESC
         LIMIT 1"
    );
    if ($filingStmt) {
        $filingStmt->bind_param('i', $orgId);
        $filingStmt->execute();
        $filingResult = $filingStmt->get_result();
        $filingAddress = $filingResult ? $filingResult->fetch_assoc() : null;
        $filingStmt->close();
    }
}

$logoPreview = !empty($settings['logo_path']) && file_exists(__DIR__ . '/' . $settings['logo_path'])
    ? $settings['logo_path']
    : null;
$publicDomain = $settings['primary_contact_email'] && preg_match('/@(gmail|yahoo|hotmail|outlook)\./i', $settings['primary_contact_email']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Organisation Profile | 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">
</head>
<body class="orgprofile-page">
  <?php settings_render_header($org['organisation_name'] ?? ($_SESSION['org_name'] ?? 'demo'), 'dashboard.php', 'fa-file-lines'); ?>

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

    <section class="profile-main">
      <div class="profile-head">
        <h1>Organisation Profile</h1>
        <div class="org-id">Organisation ID: <?php echo htmlspecialchars($orgCode); ?></div>
      </div>

      <div class="profile-card">
        <div class="info-banner" style="margin-top:0;background:#fff7df;border-color:#f5df9a;">
          <i class="fa-regular fa-lightbulb"></i>
          <div>The changes made here will be reflected in your payroll forms and profile pages as well.</div>
        </div>

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

        <form method="POST">
          <div class="logo-block">
            <div class="logo-upload">
              <?php if ($logoPreview): ?>
                <img src="<?php echo htmlspecialchars($logoPreview); ?>" alt="Organisation logo" style="max-width:100%;max-height:72px;">
              <?php else: ?>
                <i class="fa-solid fa-cloud-arrow-up"></i>
                <span>UPLOAD LOGO</span>
              <?php endif; ?>
            </div>
            <div class="logo-note">
              <div>This logo will be displayed on documents such as Payslip and TDS Worksheet.</div>
              <div class="logo-meta">Preferred size: 240 x 240 pixels at 72 DPI, maximum size 1 MB. Accepted formats: PNG, JPG, JPEG.</div>
            </div>
          </div>

          <div class="field-group">
            <label>Organisation Name<span class="req">*</span></label>
            <p class="hint">This is your registered business name which will appear in forms and payslips.</p>
            <input type="text" name="organisation_name" value="<?php echo htmlspecialchars($org['organisation_name'] ?? ''); ?>" required>
          </div>

          <div class="grid-two">
            <div class="field-group">
              <label>Business Location<span class="req">*</span></label>
              <input type="text" name="business_location" value="<?php echo htmlspecialchars($org['business_location'] ?? 'India'); ?>" required>
            </div>
            <div class="field-group">
              <label>Industry<span class="req">*</span></label>
              <select name="industry" required>
                <?php
                $industries = ['Technology', 'IT', 'Finance', 'Manufacturing', 'Education', 'Healthcare', 'Consulting'];
                $selectedIndustry = $org['industry'] ?? 'Technology';
                foreach ($industries as $industry): ?>
                  <option value="<?php echo htmlspecialchars($industry); ?>" <?php echo $selectedIndustry === $industry ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($industry); ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>

          <div class="grid-two">
            <div class="field-group">
              <label>Date Format<span class="req">*</span></label>
              <select name="date_format">
                <?php
                $dateFormats = [
                    'dd/MM/yyyy' => date('d/m/Y'),
                    'MM/dd/yyyy' => date('m/d/Y'),
                    'yyyy-MM-dd' => date('Y-m-d'),
                ];
                foreach ($dateFormats as $value => $example): ?>
                  <option value="<?php echo htmlspecialchars($value); ?>" <?php echo ($settings['date_format'] ?? '') === $value ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($value . ' [ ' . $example . ' ]'); ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="field-group">
              <label>Field Separator</label>
              <select name="field_separator">
                <?php foreach (['/', '-', '.'] as $separator): ?>
                  <option value="<?php echo htmlspecialchars($separator); ?>" <?php echo ($settings['field_separator'] ?? '/') === $separator ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($separator); ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>

          <div class="field-group">
            <label>Organisation Address<span class="req">*</span></label>
            <p class="hint">This will be considered as the address of your primary work location.</p>
            <input type="text" name="address_line1" placeholder="Address Line 1" value="<?php echo htmlspecialchars($org['address_line1'] ?? ''); ?>" required>
            <input type="text" name="address_line2" placeholder="Address Line 2" value="<?php echo htmlspecialchars($org['address_line2'] ?? ''); ?>">
          </div>

          <div class="grid-three">
            <div class="field-group">
              <label>State<span class="req">*</span></label>
              <select name="state" required>
                <option value="">Select a state</option>
                <?php foreach ($states as $state): ?>
                  <option value="<?php echo htmlspecialchars($state); ?>" <?php echo ($org['state'] ?? '') === $state ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($state); ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="field-group">
              <label>City</label>
              <input type="text" name="city" value="<?php echo htmlspecialchars($org['city'] ?? ''); ?>">
            </div>
            <div class="field-group">
              <label>PIN Code</label>
              <input type="text" name="pincode" value="<?php echo htmlspecialchars($org['pincode'] ?? ''); ?>">
            </div>
          </div>

          <div class="field-group">
            <label>Filing Address</label>
            <p class="hint">This registered address will be used across forms and payslips.</p>
            <div class="address-card">
              <div class="address-title"><?php echo htmlspecialchars($filingAddress['location_name'] ?? 'Head Office'); ?></div>
              <div><?php echo htmlspecialchars($filingAddress['address_line1'] ?? ($org['address_line1'] ?? '')); ?></div>
              <?php if (!empty($filingAddress['address_line2'])): ?>
                <div class="address-meta"><?php echo htmlspecialchars($filingAddress['address_line2']); ?></div>
              <?php endif; ?>
              <div class="address-meta">
                <?php echo htmlspecialchars(trim(($filingAddress['city'] ?? ($org['city'] ?? '')) . ', ' . ($filingAddress['state'] ?? ($org['state'] ?? '')) . ' ' . ($filingAddress['pincode'] ?? ($org['pincode'] ?? '')))); ?>
              </div>
              <a class="address-change" href="locations.php">Change</a>
            </div>
          </div>

          <div class="field-group">
            <label>Contact Information</label>
          </div>

          <div class="contact-grid">
            <div class="contact-card">
              <h3>Primary Contact Email Address</h3>
              <div class="muted">This email address receives reminders and email notifications from payroll.</div>
              <div class="field-group">
                <input type="text" name="primary_contact_name" placeholder="Primary contact name" value="<?php echo htmlspecialchars($settings['primary_contact_name'] ?? ''); ?>">
                <input type="email" name="primary_contact_email" placeholder="Primary contact email" value="<?php echo htmlspecialchars($settings['primary_contact_email'] ?? ''); ?>">
              </div>
            </div>

            <div class="contact-card">
              <h3>Emails Are Sent Through</h3>
              <div class="muted">You can configure the email address used in the sender field for emails sent via payroll.</div>
              <div class="field-group">
                <input type="email" name="sender_email" value="<?php echo htmlspecialchars($settings['sender_email'] ?? 'message-service@mail.zohopayroll.in'); ?>">
              </div>
            </div>
          </div>

          <?php if ($publicDomain): ?>
            <div class="info-banner">
              <i class="fa-solid fa-circle-info"></i>
              <div>Your primary contact email address belongs to a public domain, so emails are sent from the configured sender address to improve delivery.</div>
            </div>
          <?php endif; ?>

          <a class="config-link" href="sender_email_preferences.php">Configure Sender Email Preferences</a>

          <div class="profile-footer" style="margin-top:28px;">
            <button class="save-btn" type="submit">Save</button>
            <div class="required-note">* indicates mandatory fields</div>
          </div>
        </form>
      </div>
    </section>
  </main>
</body>
</html>
