<?php

declare(strict_types=1);
require DENTAL_ROOT . '/app/bootstrap.php';
require_login();
require_roles(['super_admin','clinic_admin']);
require DENTAL_ROOT . '/app/layout.php';

$error='';
$uploadDir=DENTAL_ROOT . '/public/uploads/branding';
if(!is_dir($uploadDir))@mkdir($uploadDir,0775,true);

function save_brand_upload(string $field,string $prefix,array $allowed,int $maxBytes): ?string
{
    global $uploadDir;
    if(empty($_FILES[$field])||($_FILES[$field]['error']??UPLOAD_ERR_NO_FILE)===UPLOAD_ERR_NO_FILE)return null;
    $file=$_FILES[$field];
    if(($file['error']??UPLOAD_ERR_OK)!==UPLOAD_ERR_OK)throw new RuntimeException('The '.$field.' upload failed.');
    if((int)$file['size']>$maxBytes)throw new RuntimeException('The '.$field.' file is too large.');
    $finfo=new finfo(FILEINFO_MIME_TYPE);$mime=$finfo->file((string)$file['tmp_name']);
    if(!isset($allowed[$mime]))throw new RuntimeException('Unsupported '.$field.' file type.');
    $name=$prefix.'-'.date('YmdHis').'-'.bin2hex(random_bytes(3)).'.'.$allowed[$mime];
    if(!move_uploaded_file((string)$file['tmp_name'],$uploadDir.'/'.$name))throw new RuntimeException('The '.$field.' file could not be saved.');
    return 'public/uploads/branding/'.$name;
}

if($_SERVER['REQUEST_METHOD']==='POST'){
    try{
        verify_csrf();
        $primary=(string)($_POST['primary']??'#0f766e');$secondary=(string)($_POST['secondary']??'#17324d');$accent=(string)($_POST['accent']??'#e6a23c');
        foreach([$primary,$secondary,$accent] as $color)if(!preg_match('/^#[0-9A-Fa-f]{6}$/',$color))throw new RuntimeException('Use valid six-digit color values.');
        $logo=save_brand_upload('logo','logo',['image/png'=>'png','image/jpeg'=>'jpg','image/webp'=>'webp'],2*1024*1024);
        $favicon=save_brand_upload('favicon','favicon',['image/png'=>'png','image/x-icon'=>'ico','image/vnd.microsoft.icon'=>'ico'],512*1024);
        setting_set('branding','name',trim((string)($_POST['name']??''))?:public_clinic_profile()['name']);
        setting_set('branding','short_name',substr(trim((string)($_POST['short_name']??'DC'))?:'DC',0,5));
        setting_set('branding','primary',$primary);setting_set('branding','secondary',$secondary);setting_set('branding','accent',$accent);
        if($logo)setting_set('branding','logo',$logo);if($favicon)setting_set('branding','favicon',$favicon);
        if(license_feature('white_label'))setting_set('branding','footer_text',trim((string)($_POST['footer_text']??''))?:'Powered by Syllabuild');
        audit('branding_updated','system',null,['logo_changed'=>(bool)$logo,'favicon_changed'=>(bool)$favicon]);flash('success','Branding has been updated.');header('Location: branding.php');exit;
    }catch(Throwable $e){$error=$e->getMessage();}
}
$brand=branding_profile();$license=dental_license_status();
render_header('Branding');
?>
<div class="tabs"><a href="settings.php">Landing Page Editor</a><a class="active">Branding &amp; Identity</a><a href="index.php" target="_blank" rel="noopener">Preview Public Website</a></div>
<?php if($error):?><div class="flash error"><?=e($error)?></div><?php endif;?>
<div class="grid two"><form method="post" enctype="multipart/form-data" class="card form-grid"><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><h2 class="wide">Clinic brand</h2><label>Brand name<input name="name" maxlength="150" value="<?=e($brand['name'])?>" required></label><label>Short mark<input name="short_name" maxlength="5" value="<?=e($brand['short_name'])?>" required></label><label>Primary color<input type="color" name="primary" value="<?=e($brand['primary'])?>"></label><label>Secondary color<input type="color" name="secondary" value="<?=e($brand['secondary'])?>"></label><label>Accent color<input type="color" name="accent" value="<?=e($brand['accent'])?>"></label><span></span><label>Logo<input type="file" name="logo" accept="image/png,image/jpeg,image/webp"><small>PNG, JPG, or WebP. Maximum 2 MB.</small></label><label>Favicon<input type="file" name="favicon" accept="image/png,image/x-icon"><small>PNG or ICO. Maximum 512 KB.</small></label><label class="wide">Footer text<input name="footer_text" maxlength="190" value="<?=e($brand['footer_text'])?>" <?=license_feature('white_label')?'':'readonly'?>></label><?php if(!license_feature('white_label')):?><div class="public-notice wide">Custom footer branding requires a white-label license.</div><?php endif;?><button class="btn primary" type="submit">Save branding</button></form><div class="card"><h2>Preview</h2><div class="brand-preview" style="--preview-primary:<?=e($brand['primary'])?>;--preview-secondary:<?=e($brand['secondary'])?>;--preview-accent:<?=e($brand['accent'])?>"><?php if($brand['logo']):?><img src="<?=e($brand['logo'])?>" alt="Current logo"><?php else:?><div class="preview-mark"><?=e($brand['short_name'])?></div><?php endif;?><h3><?=e($brand['name'])?></h3><button type="button">Appointment button</button><small><?=e($brand['footer_text'])?></small></div><h3>License</h3><dl class="summary"><div>Domain</div><div><code><?=e(dental_current_host())?></code></div><div>Status</div><div><?=e($license['message']??'Unknown')?></div><div>White label</div><div><?=license_feature('white_label')?'Enabled':'Not included'?></div></dl><?php if(superuser_primary_workspace()):?><a class="btn ghost" href="license.php">View license</a><?php else:?><p class="muted">License controls are available to the Superuser only.</p><?php endif;?></div></div>
<?php render_footer();?>
