<?php
/**
 * Enterprise HRM ERP System - Edit Branch/Site
 */

require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/check_admin_access.php';

$pageTitle = 'Edit Branch';
$currentModule = 'settings';

$siteId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($siteId <= 0) {
    redirect(BASE_URL . '/admin/sites.php', 'Invalid branch ID.', 'error');
}

$errors = [];
$formData = [];

// Load site data
try {
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM sites WHERE site_id = ?");
    $stmt->execute([$siteId]);
    $site = $stmt->fetch();
    
    if (!$site) {
        redirect(BASE_URL . '/admin/sites.php', 'Branch not found.', 'error');
    }
    
    $formData = [
        'site_code' => $site['site_code'],
        'site_name' => $site['site_name'],
        'site_address' => $site['site_address'] ?? '',
        'site_phone' => $site['site_phone'] ?? '',
        'site_email' => $site['site_email'] ?? '',
        'site_status' => $site['site_status'],
    ];
} catch (Exception $e) {
    error_log("Error loading site: " . $e->getMessage());
    redirect(BASE_URL . '/admin/sites.php', 'Error loading branch data.', 'error');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'site_code' => sanitize($_POST['site_code'] ?? ''),
        'site_name' => sanitize($_POST['site_name'] ?? ''),
        'site_address' => sanitize($_POST['site_address'] ?? ''),
        'site_phone' => sanitize($_POST['site_phone'] ?? ''),
        'site_email' => sanitize($_POST['site_email'] ?? ''),
        'site_status' => sanitize($_POST['site_status'] ?? 'active'),
    ];
    
    // Validation
    if (empty($formData['site_code'])) {
        $errors[] = 'Branch code is required.';
    } elseif (strlen($formData['site_code']) < 2) {
        $errors[] = 'Branch code must be at least 2 characters.';
    } elseif (!preg_match('/^[A-Z0-9_]+$/', $formData['site_code'])) {
        $errors[] = 'Branch code can only contain uppercase letters, numbers, and underscores.';
    }
    
    if (empty($formData['site_name'])) {
        $errors[] = 'Branch name is required.';
    } elseif (strlen($formData['site_name']) < 3) {
        $errors[] = 'Branch name must be at least 3 characters.';
    }
    
    if (!empty($formData['site_email']) && !filter_var($formData['site_email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Invalid email format.';
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            $db->beginTransaction();
            
            // Check if site_code already exists (excluding current site)
            $stmt = $db->prepare("SELECT site_id FROM sites WHERE site_code = ? AND site_id != ?");
            $stmt->execute([$formData['site_code'], $siteId]);
            if ($stmt->fetch()) {
                $errors[] = 'Branch code already exists. Please use a different code.';
                $db->rollBack();
            } else {
                // Update site
                $stmt = $db->prepare("
                    UPDATE sites SET
                        site_code = ?,
                        site_name = ?,
                        site_address = ?,
                        site_phone = ?,
                        site_email = ?,
                        site_status = ?,
                        updated_at = NOW()
                    WHERE site_id = ?
                ");
                $stmt->execute([
                    strtoupper($formData['site_code']),
                    $formData['site_name'],
                    $formData['site_address'] ?: null,
                    $formData['site_phone'] ?: null,
                    $formData['site_email'] ?: null,
                    $formData['site_status'],
                    $siteId
                ]);
                
                $db->commit();
                
                // Log audit
                logAudit('UPDATE', 'sites', $siteId);
                
                // Update session if this is the current site
                if (isset($_SESSION['site_id']) && $_SESSION['site_id'] == $siteId) {
                    $_SESSION['site_name'] = $formData['site_name'];
                    $_SESSION['site_code'] = $formData['site_code'];
                }
                
                redirect(BASE_URL . '/admin/sites.php', 'Branch updated successfully.');
            }
            
        } catch (Exception $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            error_log("Error updating branch: " . $e->getMessage());
            $errors[] = 'An error occurred while updating branch. Please try again.';
        }
    }
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Edit Branch</h2>
        <a href="<?php echo BASE_URL; ?>/admin/sites.php" class="btn btn-secondary">Back to Branches</a>
    </div>
    
    <?php if (!empty($errors)): ?>
    <div class="alert alert-error">
        <ul style="margin: 0; padding-left: 20px;">
            <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>
    
    <form method="POST" id="branchForm" style="margin-top: 20px;">
        <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">
            <div class="form-group">
                <label class="form-label" for="site_code">Branch Code *</label>
                <input type="text" id="site_code" name="site_code" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['site_code'] ?? ''); ?>"
                       pattern="[A-Z0-9_]+" 
                       style="text-transform: uppercase;"
                       placeholder="e.g., BRANCH01, DELHI_01"
                       minlength="2" maxlength="50">
                <small style="color: var(--text-secondary);">Uppercase letters, numbers, and underscores only</small>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="site_name">Branch Name *</label>
                <input type="text" id="site_name" name="site_name" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['site_name'] ?? ''); ?>"
                       placeholder="e.g., Delhi Branch, Mumbai Office"
                       minlength="3" maxlength="255">
            </div>
            
            <div class="form-group" style="grid-column: 1 / -1;">
                <label class="form-label" for="site_address">Address</label>
                <textarea id="site_address" name="site_address" class="form-control" rows="3"
                          placeholder="Enter branch address"><?php echo htmlspecialchars($formData['site_address'] ?? ''); ?></textarea>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="site_phone">Phone</label>
                <input type="tel" id="site_phone" name="site_phone" class="form-control"
                       value="<?php echo htmlspecialchars($formData['site_phone'] ?? ''); ?>"
                       placeholder="e.g., +91-1234567890">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="site_email">Email</label>
                <input type="email" id="site_email" name="site_email" class="form-control"
                       value="<?php echo htmlspecialchars($formData['site_email'] ?? ''); ?>"
                       placeholder="e.g., branch@company.com">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="site_status">Status *</label>
                <select id="site_status" name="site_status" class="form-control" required>
                    <option value="active" <?php echo ($formData['site_status'] ?? 'active') === 'active' ? 'selected' : ''; ?>>Active</option>
                    <option value="inactive" <?php echo ($formData['site_status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                </select>
            </div>
        </div>
        
        <div style="margin-top: 30px; text-align: right; padding-top: 20px; border-top: 1px solid var(--border-color);">
            <a href="<?php echo BASE_URL; ?>/admin/sites.php" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Update Branch</button>
        </div>
    </form>
</div>

<script>
// Auto-uppercase branch code
document.getElementById('site_code').addEventListener('input', function(e) {
    this.value = this.value.toUpperCase().replace(/[^A-Z0-9_]/g, '');
});

document.getElementById('branchForm').addEventListener('submit', function(e) {
    const siteCode = document.getElementById('site_code').value;
    
    if (!/^[A-Z0-9_]+$/.test(siteCode)) {
        e.preventDefault();
        alert('Branch code can only contain uppercase letters, numbers, and underscores!');
        return false;
    }
    
    if (siteCode.length < 2) {
        e.preventDefault();
        alert('Branch code must be at least 2 characters long!');
        return false;
    }
});
</script>

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

