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

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

// Fetch kiosk user details
$kiosk_user = fetch("SELECT id, username FROM users WHERE company_id = ? AND role = 'kiosk' LIMIT 1", [$company_id]);
$kiosk_username = $kiosk_user ? $kiosk_user['username'] : 'kiosk_' . $company_id;

$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $website = $_POST['website'];
    $address = $_POST['address'];
    $currency = $_POST['currency'] ?? '$';
    
    // Kiosk credentials inputs
    $new_kiosk_username = trim($_POST['kiosk_username'] ?? '');
    $new_kiosk_password = $_POST['kiosk_password'] ?? '';
    
    // Validate Kiosk Username uniqueness if specified
    if (!empty($new_kiosk_username)) {
        // If kiosk user already exists, exclude them from uniqueness check
        $kiosk_id = $kiosk_user ? $kiosk_user['id'] : 0;
        $existing_user = fetch(
            "SELECT id FROM users WHERE username = ? AND id != ?", 
            [$new_kiosk_username, $kiosk_id]
        );
        if ($existing_user) {
            $error_message = "The Kiosk username '$new_kiosk_username' is already taken by another user.";
        }
    } else {
        $error_message = "Kiosk username cannot be empty.";
    }
    
    if (empty($error_message)) {
        // 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/';
            
            // Create upload dir if it doesn't exist
            if (!file_exists($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }
            
            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 = ?, currency = ? WHERE id = ?", 
              [$name, $email, $phone, $website, $address, $logo_path, $currency, $_SESSION['company_id']]);
              
        // Create or Update Kiosk user credentials
        if ($kiosk_user) {
            if (!empty($new_kiosk_password)) {
                $hashed_pass = password_hash($new_kiosk_password, PASSWORD_DEFAULT);
                query(
                    "UPDATE users SET username = ?, password = ? WHERE id = ?",
                    [$new_kiosk_username, $hashed_pass, $kiosk_user['id']]
                );
            } else {
                query(
                    "UPDATE users SET username = ? WHERE id = ?",
                    [$new_kiosk_username, $kiosk_user['id']]
                );
            }
        } else {
            $pass_to_use = !empty($new_kiosk_password) ? $new_kiosk_password : 'kiosk123';
            $hashed_pass = password_hash($pass_to_use, PASSWORD_DEFAULT);
            query(
                "INSERT INTO users (name, username, email, password, role, company_id, is_active) VALUES ('Attendance Kiosk', ?, ?, ?, 'kiosk', ?, 1)",
                [$new_kiosk_username, 'kiosk_' . $_SESSION['company_id'] . '@nexcore.com', $hashed_pass, $_SESSION['company_id']]
            );
        }
              
        // Update session currency
        $_SESSION['company_currency'] = $currency;
        
        logAudit('COMPANY_UPDATE', 'Updated company profile details, logo, and Kiosk credentials');
        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; ?>

    <?php if (!empty($error_message)): ?>
    <div class="card animate-fade-in" style="background: rgba(239, 68, 68, 0.1); border: 1px solid var(--danger); margin-bottom: 1.5rem; padding: 0.75rem 1rem;">
        <div style="color: var(--danger); display: flex; align-items: center; gap: 0.5rem;">
            <i class="fas fa-exclamation-circle"></i>
            <span><?php echo htmlspecialchars($error_message); ?></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">System Currency <span class="required-mark">*</span></label>
                <select name="currency" class="form-control" required>
                    <option value="$" <?php echo ($company['currency'] ?? '') === '$' ? 'selected' : ''; ?>>USD ($)</option>
                    <option value="€" <?php echo ($company['currency'] ?? '') === '€' ? 'selected' : ''; ?>>EUR (€)</option>
                    <option value="£" <?php echo ($company['currency'] ?? '') === '£' ? 'selected' : ''; ?>>GBP (£)</option>
                    <option value="¥" <?php echo ($company['currency'] ?? '') === '¥' ? 'selected' : ''; ?>>JPY (¥)</option>
                    <option value="₹" <?php echo ($company['currency'] ?? '') === '₹' ? 'selected' : ''; ?>>INR (₹)</option>
                    <option value="LKR" <?php echo ($company['currency'] ?? '') === 'LKR' ? 'selected' : ''; ?>>LKR (Rs)</option>
                    <option value="AUD" <?php echo ($company['currency'] ?? '') === 'AUD' ? 'selected' : ''; ?>>AUD ($)</option>
                    <option value="CAD" <?php echo ($company['currency'] ?? '') === 'CAD' ? 'selected' : ''; ?>>CAD ($)</option>
                </select>
                <p style="font-size: 0.75rem; color: var(--text-muted); margin-top: 0.25rem;">This currency will be used across all reports, inventory costs, and employee rates.</p>
            </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>

            <!-- Kiosk Mode Access Credentials -->
            <div style="margin-top: 2rem; border-top: 1px solid var(--border); padding-top: 1.5rem;">
                <h3 style="font-size: 1.1rem; font-weight: 600; color: var(--text-main); margin-bottom: 0.5rem; display: flex; align-items: center; gap: 0.5rem;">
                    <i class="fas fa-tablet-alt" style="color: var(--primary);"></i>
                    Kiosk Access Credentials
                </h3>
                <p style="color: var(--text-muted); font-size: 0.85rem; margin-bottom: 1.25rem;">
                    Configure a dedicated login account for the entrance tablet. This account will be locked directly to the attendance scan screen and will not have access to dashboard management features.
                </p>
                
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                    <div class="form-group">
                        <label class="form-label">Kiosk Username <span class="required-mark">*</span></label>
                        <input type="text" name="kiosk_username" class="form-control" value="<?php echo htmlspecialchars($kiosk_username); ?>" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Kiosk Password</label>
                        <input type="password" name="kiosk_password" class="form-control" placeholder="<?php echo $kiosk_user ? 'Leave blank to keep current' : 'Default: kiosk123'; ?>">
                    </div>
                </div>
            </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>
