<?php
require_once 'includes/db.php';
requireRole('owner');

$company_id = $_SESSION['company_id'] ?? 0;
$company = fetch("SELECT * FROM companies WHERE id = ?", [$company_id]) ?: [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $website = $_POST['website'];
    $address = $_POST['address'];
    
    // Handle Logo Upload
    $logo_path = $company['logo'];
    if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
        $fileTmpPath = $_FILES['logo']['tmp_name'];
        $fileName = $_FILES['logo']['name'];
        $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        $newFileName = 'logo_' . $_SESSION['company_id'] . '_' . time() . '.' . $fileExtension;
        $uploadDir = 'assets/uploads/company/';
        
        if (move_uploaded_file($fileTmpPath, $uploadDir . $newFileName)) {
            // Delete old logo if exists
            if ($logo_path && file_exists($uploadDir . basename($logo_path))) {
                @unlink($uploadDir . basename($logo_path));
            }
            $logo_path = $uploadDir . $newFileName;
        }
    }
    
    query("UPDATE companies SET name = ?, email = ?, phone = ?, website = ?, address = ?, logo = ? WHERE id = ?", 
          [$name, $email, $phone, $website, $address, $logo_path, $_SESSION['company_id']]);
    
    logAudit('COMPANY_UPDATE', 'Updated company profile details and logo');
    header("Location: " . url('company-settings', ['success' => 1]));
    exit;
}
?>

<style>
    .required-mark { color: var(--danger); margin-left: 2px; }
</style>

<div style="max-width: 800px; margin: 0 auto;">
    <div style="margin-bottom: 2rem;">
        <p style="color: var(--text-muted); margin-bottom: 2rem;">Manage your organization's primary identity and contact information</p>
    </div>

    <?php if (isset($_GET['success'])): ?>
    <div class="card animate-fade-in" style="background: rgba(16, 185, 129, 0.1); border: 1px solid var(--success); margin-bottom: 1.5rem; padding: 0.75rem 1rem;">
        <div style="color: var(--success); display: flex; align-items: center; gap: 0.5rem;">
            <i class="fas fa-check-circle"></i>
            <span>Company profile updated successfully!</span>
        </div>
    </div>
    <?php endif; ?>

    <div class="card">
        <form method="POST" action="" enctype="multipart/form-data">
            <div style="display: flex; gap: 2rem; margin-bottom: 2rem; align-items: center;">
                <div style="width: 100px; height: 100px; border-radius: 20px; background: var(--bg-dark); display: flex; align-items: center; justify-content: center; border: 2px dashed var(--border); overflow: hidden;">
                    <img id="logo-preview" src="<?php echo $company['logo'] ?? ''; ?>" style="width: 100%; height: 100%; object-fit: contain; <?php echo !($company['logo'] ?? '') ? 'display: none;' : ''; ?>">
                    <i id="logo-placeholder" class="fas fa-building fa-2x" style="color: var(--text-muted); <?php echo ($company['logo'] ?? '') ? 'display: none;' : ''; ?>"></i>
                </div>
                <div>
                    <label for="logo_upload" class="btn" style="background: var(--bg-dark); font-size: 0.85rem; cursor: pointer;">
                        <i class="fas fa-upload"></i> <?php echo ($company['logo'] ?? '') ? 'Change Logo' : 'Upload Logo'; ?>
                    </label>
                    <input type="file" id="logo_upload" name="logo" style="display: none;" accept="image/*" onchange="previewLogo(this)">
                    <p style="font-size: 0.75rem; color: var(--text-muted); margin-top: 0.5rem;">Recommended size: 200x200px. PNG, JPG or SVG.</p>
                </div>
            </div>

            <script>
            function previewLogo(input) {
                if (input.files && input.files[0]) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        const preview = document.getElementById('logo-preview');
                        const placeholder = document.getElementById('logo-placeholder');
                        preview.src = e.target.result;
                        preview.style.display = 'block';
                        placeholder.style.display = 'none';
                    }
                    reader.readAsDataURL(input.files[0]);
                }
            }
            </script>

            <div class="form-group">
                <label class="form-label">Company Name <span class="required-mark">*</span></label>
                <input type="text" name="name" class="form-control" value="<?php echo htmlspecialchars($company['name'] ?? ''); ?>" required>
            </div>

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                <div class="form-group">
                    <label class="form-label">Email Address</label>
                    <input type="email" name="email" class="form-control" value="<?php echo htmlspecialchars($company['email'] ?? ''); ?>">
                </div>
                <div class="form-group">
                    <label class="form-label">Phone Number <span class="required-mark">*</span></label>
                    <input type="tel" name="phone" class="form-control" value="<?php echo htmlspecialchars($company['phone'] ?? ''); ?>" required>
                </div>
            </div>

            <div class="form-group">
                <label class="form-label">Website</label>
                <input type="url" name="website" class="form-control" value="<?php echo htmlspecialchars($company['website'] ?? ''); ?>" placeholder="https://example.com">
            </div>

            <div class="form-group">
                <label class="form-label">Physical Address <span class="required-mark">*</span></label>
                <textarea name="address" class="form-control" rows="3" required><?php echo htmlspecialchars($company['address'] ?? ''); ?></textarea>
            </div>

            <div style="margin-top: 2rem; border-top: 1px solid var(--border); padding-top: 1.5rem; display: flex; justify-content: flex-end;">
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-save"></i> Save Company Details
                </button>
            </div>
        </form>
    </div>
</div>
