<?php
// FIXED PATH: 3 folders up gets us perfectly to the 'application' root, then into dripend.
require_once __DIR__ . '/../../../dripend/includes/db.php';

// Fetch the live facility configuration directly from the database
$query = "SELECT * FROM facility_profile WHERE id = 1 LIMIT 1";
$result = mysqli_query($conn, $query);
$profile = mysqli_fetch_object($result);

// If database row exists, set the toggle switches automatically
if ($profile) {
    $profile->enable_secondary_phone = !empty($profile->secondary_phone) ? 1 : 0;
    $profile->enable_secondary_email = !empty($profile->secondary_email) ? 1 : 0;
} else {
    // Fallback logic only if the database is entirely empty
    $profile = (object)[
        'hospital_name' => 'Central Tertiary Hospital',
        'tax_id' => '',
        'primary_phone' => '+233 24 123 4567',
        'enable_secondary_phone' => 0, 
        'secondary_phone' => '',
        'primary_email' => 'info@rimaxhealth.com',
        'enable_secondary_email' => 0, 
        'secondary_email' => '',
        'address' => 'Ridge, Accra',
        'postal_address' => '',
        'enable_dual_logo' => 0,
        'primary_logo_path' => '',
        'secondary_logo_path' => '',
        'document_alignment' => 'center',
        'primary_hex' => '#1E3A8A',
        'accent_hex' => '#3B82F6',
        'id_format' => 'FMT_B',
        'id_padding' => 5,
        'opd_prefix' => 'RMX',
        'print_format' => 'CR80',
        'scannable_code_type' => 'QR',
        'print_photo' => 1,
        'print_blood_group' => 1
    ];
}
?>

<link rel="stylesheet" href="../../assets/css/fac-profile.css">

<div class="fac-module">
    <div class="fac-header-area">
        <div class="fac-page-title"><i class="fa-solid fa-hospital"></i> Facility Profile & Branding</div>
        <div class="fac-page-subtitle">Configure identity, contact details, ID sequences, and print formatting rules for this facility.</div>
    </div>

    <form action="/rimax/application/dripend/systemSetup/facility/updateProfile.php" method="POST" enctype="multipart/form-data">
        <div class="fac-split-layout">
            
            <div class="fac-panel fac-panel-left">
                <div class="fac-panel-title"><i class="fa-solid fa-palette"></i> Letterhead & Branding</div>
                
                <div class="fac-toggle-container">
                    <div>
                        <span class="fac-toggle-text">Enable Dual-Logo Layout</span>
                        <span class="fac-toggle-desc">Use a split header for official documents.</span>
                    </div>
                    <label class="switch">
                        <input type="checkbox" id="dualLogoToggle" name="enable_dual_logo" value="1" <?php echo ($profile->enable_dual_logo == 1) ? 'checked' : ''; ?> onchange="toggleDualLogo(this)">
                        <span class="slider"></span>
                    </label>
                </div>

                <div class="fac-dual-logo-wrapper">
                    <div class="fac-logo-container" id="primaryLogoSection">
                        <span style="font-size: 11px; font-weight: 800; color: #1e293b; margin-bottom: 12px; text-transform:uppercase;">Primary / Left</span>
                        <div class="fac-logo-preview" id="primaryLogoBox">
                            <?php if(!empty($profile->primary_logo_path)): ?>
                                <img id="primaryImg" src="/rimax/application/<?php echo htmlspecialchars($profile->primary_logo_path); ?>" alt="Primary Logo" style="display:block; width:100%; height:100%; object-fit:contain; padding:10px;">
                                <i class="fa-solid fa-hospital fac-logo-placeholder" id="primaryPlaceholder" style="display:none;"></i>
                            <?php else: ?>
                                <img id="primaryImg" src="" alt="Primary Logo" style="display:none; width:100%; height:100%; object-fit:contain; padding:10px;">
                                <i class="fa-solid fa-hospital fac-logo-placeholder" id="primaryPlaceholder"></i>
                            <?php endif; ?>
                        </div>
                        <label class="fac-upload-btn">
                            <i class="fa-solid fa-cloud-arrow-up"></i> Upload
                            <input type="file" id="primaryUpload" name="primary_logo" class="fac-file-input" accept=".png, .jpg, .svg" onchange="previewImage(this, 'primaryImg', 'primaryPlaceholder')">
                        </label>
                    </div>

                    <div class="fac-logo-container" id="secondaryLogoSection" style="<?php echo ($profile->enable_dual_logo == 1) ? 'display:flex;' : 'display:none;'; ?> background: #fffbeb; border-color: #fde68a;">
                        <span style="font-size: 11px; font-weight: 800; color: #92400e; margin-bottom: 12px; text-transform:uppercase;">Secondary / Right</span>
                        <div class="fac-logo-preview" id="secondaryLogoBox" style="border-color:#fcd34d;">
                            <?php if(!empty($profile->secondary_logo_path)): ?>
                                <img id="secondaryImg" src="/rimax/application/<?php echo htmlspecialchars($profile->secondary_logo_path); ?>" alt="Secondary Logo" style="display:block; width:100%; height:100%; object-fit:contain; padding:10px;">
                                <i class="fa-solid fa-shield-cat fac-logo-placeholder" id="secondaryPlaceholder" style="display:none;"></i>
                            <?php else: ?>
                                <img id="secondaryImg" src="" alt="Secondary Logo" style="display:none; width:100%; height:100%; object-fit:contain; padding:10px;">
                                <i class="fa-solid fa-shield-cat fac-logo-placeholder" id="secondaryPlaceholder" style="color:#fbbf24;"></i>
                            <?php endif; ?>
                        </div>
                        <label class="fac-upload-btn" style="border-color:#fcd34d; color:#92400e;">
                            <i class="fa-solid fa-cloud-arrow-up"></i> Upload
                            <input type="file" id="secondaryUpload" name="secondary_logo" class="fac-file-input" accept=".png, .jpg, .svg" onchange="previewImage(this, 'secondaryImg', 'secondaryPlaceholder')">
                        </label>
                    </div>
                </div>

                <div class="fac-panel-title" style="margin-top: 10px;"><i class="fa-solid fa-align-center"></i> Document Text Alignment</div>
                <div class="fac-form-row">
                    <div class="fac-form-col">
                        <label>Align Address, Email & Phone Numbers</label>
                        <div class="alignment-group">
                            <button type="button" class="align-btn <?php echo ($profile->document_alignment == 'left') ? 'active' : ''; ?>" onclick="setAlignment('left', this)"><i class="fa-solid fa-align-left"></i> Left</button>
                            <button type="button" class="align-btn <?php echo ($profile->document_alignment == 'center') ? 'active' : ''; ?>" onclick="setAlignment('center', this)"><i class="fa-solid fa-align-center"></i> Center</button>
                            <button type="button" class="align-btn <?php echo ($profile->document_alignment == 'right') ? 'active' : ''; ?>" onclick="setAlignment('right', this)"><i class="fa-solid fa-align-right"></i> Right</button>
                            <input type="hidden" id="headerAlignmentValue" name="document_alignment" value="<?php echo htmlspecialchars($profile->document_alignment); ?>">
                        </div>
                    </div>
                </div>
                
                <div class="fac-panel-title" style="margin-top: 20px;"><i class="fa-solid fa-fill-drip"></i> Theme Colors</div>
                <div class="fac-form-row" style="margin-bottom:0;">
                    <div class="fac-form-col">
                        <label>Primary Hex</label>
                        <div class="color-picker-wrap">
                            <input type="color" class="color-picker" name="primary_hex" value="<?php echo htmlspecialchars($profile->primary_hex); ?>" id="primaryColor" oninput="updateColorSync(this, 'primaryHex', true)">
                            <span class="color-hex" id="primaryHex"><?php echo htmlspecialchars($profile->primary_hex); ?></span>
                        </div>
                    </div>
                    <div class="fac-form-col">
                        <label>Accent Hex</label>
                        <div class="color-picker-wrap">
                            <input type="color" class="color-picker" name="accent_hex" value="<?php echo htmlspecialchars($profile->accent_hex); ?>" id="accentColor" oninput="updateColorSync(this, 'accentHex', false)">
                            <span class="color-hex" id="accentHex"><?php echo htmlspecialchars($profile->accent_hex); ?></span>
                        </div>
                    </div>
                </div>
            </div>

            <div class="fac-panel fac-panel-right">
                <div class="fac-panel-title"><i class="fa-solid fa-building"></i> Facility & Contact Information</div>
                
                <div class="fac-form-row">
                    <div class="fac-form-col" style="flex: 2;">
                        <label>Hospital / Facility Name <span style="color:#dc2626;">*</span></label>
                        <input type="text" class="fac-input" name="hospital_name" id="hospitalNameInput" value="<?php echo htmlspecialchars($profile->hospital_name); ?>" required onkeyup="updateIdPreview()">
                    </div>
                    <div class="fac-form-col" style="flex: 1;">
                        <label>Tax ID / TIN Number</label>
                        <input type="text" class="fac-input" name="tax_id" value="<?php echo htmlspecialchars($profile->tax_id); ?>">
                    </div>
                </div>
                
                <div class="fac-form-row">
                    <div class="fac-form-col">
                        <label>Primary Phone <span style="color:#dc2626;">*</span></label>
                        <input type="text" class="fac-input" name="primary_phone" value="<?php echo htmlspecialchars($profile->primary_phone); ?>" required>
                    </div>
                    <div class="fac-form-col">
                        <div class="fac-slim-toggle">
                            <label>Secondary Phone</label>
                            <label class="switch switch-sm">
                                <input type="checkbox" id="phoneToggle" name="enable_secondary_phone" value="1" <?php echo ($profile->enable_secondary_phone == 1) ? 'checked' : ''; ?> onchange="toggleSecondaryPhone(this)">
                                <span class="slider"></span>
                            </label>
                        </div>
                        <input type="text" class="fac-input" name="secondary_phone" id="secondaryPhoneInput" value="<?php echo htmlspecialchars($profile->secondary_phone); ?>" style="<?php echo ($profile->enable_secondary_phone == 1) ? 'display:block;' : 'display:none;'; ?>" placeholder="e.g. +233 54 123 4567">
                    </div>
                </div>

                <div class="fac-form-row">
                    <div class="fac-form-col">
                        <label>Primary Email <span style="color:#dc2626;">*</span></label>
                        <input type="email" class="fac-input" name="primary_email" value="<?php echo htmlspecialchars($profile->primary_email); ?>" required>
                    </div>
                    <div class="fac-form-col">
                        <div class="fac-slim-toggle">
                            <label>Secondary Email</label>
                            <label class="switch switch-sm">
                                <input type="checkbox" id="emailToggle" name="enable_secondary_email" value="1" <?php echo ($profile->enable_secondary_email == 1) ? 'checked' : ''; ?> onchange="toggleSecondaryEmail(this)">
                                <span class="slider"></span>
                            </label>
                        </div>
                        <input type="email" class="fac-input" name="secondary_email" id="secondaryEmailInput" value="<?php echo htmlspecialchars($profile->secondary_email); ?>" style="<?php echo ($profile->enable_secondary_email == 1) ? 'display:block;' : 'display:none;'; ?>" placeholder="e.g. backup@rimaxhealth.com">
                    </div>
                </div>

                <div class="fac-form-row">
                    <div class="fac-form-col">
                        <label>Physical Address / Location</label>
                        <textarea class="fac-input fac-textarea" name="address"><?php echo htmlspecialchars($profile->address); ?></textarea>
                    </div>
                    <div class="fac-form-col">
                        <label>Postal Address</label>
                        <textarea class="fac-input fac-textarea" name="postal_address"><?php echo htmlspecialchars($profile->postal_address); ?></textarea>
                    </div>
                </div>

                <div class="fac-panel-title" style="margin-top: 30px;"><i class="fa-solid fa-hashtag"></i> Patient ID Generation Sequence</div>
                
                <div class="fac-form-row">
                    <div class="fac-form-col">
                        <label>Global ID Format Structure</label>
                        <select class="fac-input" name="id_format" id="idFormatSelect" onchange="updateIdPreview()">
                            <option value="FMT_A" <?php echo ($profile->id_format == 'FMT_A') ? 'selected' : ''; ?>>[PREFIX]-[YYYY]-[MM]-[SEQ]</option>
                            <option value="FMT_B" <?php echo ($profile->id_format == 'FMT_B') ? 'selected' : ''; ?>>[PREFIX]-[YY]-[SEQ]</option>
                            <option value="FMT_C" <?php echo ($profile->id_format == 'FMT_C') ? 'selected' : ''; ?>>[PREFIX][YYYY][SEQ]</option>
                            <option value="FMT_D" <?php echo ($profile->id_format == 'FMT_D') ? 'selected' : ''; ?>>[YYYY][MM]-[PREFIX]-[SEQ]</option>
                            <option value="FMT_E" <?php echo ($profile->id_format == 'FMT_E') ? 'selected' : ''; ?>>[SEQ]-[PREFIX]-[YY]</option>
                        </select>
                    </div>
                    <div class="fac-form-col">
                        <label>Sequence Padding</label>
                        <select class="fac-input" name="id_padding" id="idPaddingSelect" onchange="updateIdPreview()">
                            <option value="4" <?php echo ($profile->id_padding == 4) ? 'selected' : ''; ?>>4 Digits (0001)</option>
                            <option value="5" <?php echo ($profile->id_padding == 5) ? 'selected' : ''; ?>>5 Digits (00001)</option>
                            <option value="6" <?php echo ($profile->id_padding == 6) ? 'selected' : ''; ?>>6 Digits (000001)</option>
                        </select>
                    </div>
                    <div class="fac-form-col">
                        <label>OPD Base Prefix <span style="color:#dc2626;">*</span></label>
                        <input type="text" class="fac-input" name="opd_prefix" id="idOpdPrefix" value="<?php echo htmlspecialchars($profile->opd_prefix); ?>" style="text-transform: uppercase;" onkeyup="updateIdPreview()">
                    </div>
                </div>

                <div class="id-preview-wrapper">
                    <span style="font-size: 11px; font-weight: 700; color: #64748b; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 12px;">Live ID Card Layout Preview</span>
                    
                    <div class="id-card" id="liveIdCard">
                        <div class="id-card-header" id="cardHeaderColor" style="background-color: <?php echo htmlspecialchars($profile->primary_hex); ?>;">
                            <i class="fa-solid fa-hospital"></i>
                            <span id="previewHospName"><?php echo htmlspecialchars($profile->hospital_name); ?></span>
                        </div>
                        <div class="id-card-body">
                            <div class="id-card-photo" id="previewPhoto">
                                <i class="fa-solid fa-user"></i>
                            </div>
                            <div class="id-card-details">
                                <div class="id-card-name">JOHN DOE</div>
                                <div class="id-card-no" id="previewIdNumber">RMX-26-00001</div>
                                <div class="id-card-meta"><strong>DOB:</strong> 15-May-1985</div>
                                <div class="id-card-meta" id="previewBlood"><strong>Blood:</strong> O+</div>
                            </div>
                        </div>
                        <div class="id-card-code" id="previewScannableCode">
                            <i class="fa-solid fa-qrcode"></i>
                        </div>
                    </div>
                </div>

                <div style="border-top: 1px solid #e2e8f0; margin-top: 20px; padding-top: 24px; text-align: right;">
                    <button type="submit" class="fac-btn-primary"><i class="fa-solid fa-floppy-disk"></i> Save Configuration</button>
                </div>
            </div>
        </div>
    </form>
</div>