<?php
declare(strict_types=1);
require __DIR__ . '/app/bootstrap.php';
require_auth();
require_current_schema();
require_permission('customers.manage');
require __DIR__ . '/app/layout.php';
require __DIR__ . '/app/actions.php';
handle_actions();

function cleanup_phone_key(?string $value): string {
    $digits=preg_replace('/\D+/','',(string)$value);
    if($digits==='')return '';
    if(str_starts_with($digits,'0'))$digits='263'.substr($digits,1);
    elseif(strlen($digits)===9&&str_starts_with($digits,'7'))$digits='263'.$digits;
    return $digits;
}
function cleanup_text_key(?string $value): string {
    return strtolower(trim(preg_replace('/[^a-z0-9]+/i',' ',(string)$value)));
}

$customers=db()->query('SELECT c.*,
    (SELECT COUNT(*) FROM documents d WHERE d.customer_id=c.id)+
    (SELECT COUNT(*) FROM web_orders w WHERE w.customer_id=c.id)+
    (SELECT COUNT(*) FROM crm_opportunities o WHERE o.customer_id=c.id)+
    (SELECT COUNT(*) FROM crm_activities a WHERE a.customer_id=c.id)+
    (SELECT COUNT(*) FROM refill_jobs r WHERE r.customer_id=c.id)+
    (SELECT COUNT(*) FROM deliveries dl WHERE dl.customer_id=c.id)+
    (SELECT COUNT(*) FROM whatsapp_conversations wc WHERE wc.customer_id=c.id)+
    (SELECT COUNT(*) FROM whatsapp_messages wm WHERE wm.customer_id=c.id)+
    (SELECT COUNT(*) FROM cylinder_assets ca WHERE ca.customer_id=c.id) linked_records,
    (SELECT COUNT(*) FROM documents d WHERE d.customer_id=c.id) document_count,
    (SELECT COUNT(*) FROM refill_jobs r WHERE r.customer_id=c.id) refill_count
    FROM customers c WHERE c.active=1 ORDER BY c.id')->fetchAll();

$byKey=[];
foreach($customers as $customer){
    $keys=[];
    $email=strtolower(trim((string)$customer['email']));if($email!=='')$keys['email:'.$email]='Same email';
    foreach([$customer['phone'],$customer['whatsapp']] as $phone){$phoneKey=cleanup_phone_key($phone);if($phoneKey!=='')$keys['phone:'.$phoneKey]='Same phone / WhatsApp';}
    $tax=cleanup_text_key($customer['tax_number']);if($tax!=='')$keys['tax:'.$tax]='Same tax number';
    $name=cleanup_text_key($customer['name']);$company=cleanup_text_key($customer['company_name']);if($name!==''&&$company!=='')$keys['identity:'.$name.'|'.$company]='Same name and company';
    foreach($keys as $key=>$reason)$byKey[$key]=['reason'=>$reason,'customers'=>array_merge($byKey[$key]['customers']??[],[$customer])];
}
$duplicateSets=[];
foreach($byKey as $group){if(count($group['customers'])<2)continue;$ids=array_map(fn($customer)=>(int)$customer['id'],$group['customers']);sort($ids);$signature=implode('-',$ids);if(isset($duplicateSets[$signature])){$duplicateSets[$signature]['reasons'][]=$group['reason'];continue;}$ordered=$group['customers'];usort($ordered,fn($a,$b)=>(int)$b['linked_records']<=>(int)$a['linked_records']?:((int)$a['id']<=>(int)$b['id']));$duplicateSets[$signature]=['reasons'=>[$group['reason']],'customers'=>$ordered];}
usort($duplicateSets,fn($a,$b)=>count($b['customers'])<=>count($a['customers']));
$duplicateIds=[];foreach($duplicateSets as $set)foreach($set['customers'] as $customer)$duplicateIds[(int)$customer['id']]=true;
$unusedDuplicates=array_values(array_filter($customers,fn($customer)=>isset($duplicateIds[(int)$customer['id']])&&(int)$customer['linked_records']===0));

render_header('Customer cleanup','customers');
?>
<div class="cleanup-heading"><div><span class="section-kicker">CUSTOMER DATA QUALITY</span><h2>Merge duplicate contacts safely</h2><p>Keep one complete customer profile while moving every linked invoice, order, CRM activity, refill, delivery and message to it.</p></div><a class="button secondary" href="index.php?page=customers">Back to customers</a></div>
<div class="cleanup-safety"><b>Protected cleanup</b><span>A duplicate with business history cannot be deleted. It must be merged so statements, balances and operational records remain correct.</span></div>

<section class="cleanup-stats"><article><span>Active customers</span><strong><?=count($customers)?></strong></article><article class="<?=count($duplicateSets)?'attention':''?>"><span>Possible duplicate groups</span><strong><?=count($duplicateSets)?></strong></article><article><span>Unused duplicate contacts</span><strong><?=count($unusedDuplicates)?></strong></article></section>

<section class="panel cleanup-manual"><div class="panel-head"><div><h2>Merge two selected customers</h2><p>Use this when you already know which records represent the same customer.</p></div></div><form method="post" class="form-grid cleanup-merge-form"><?=csrf_field()?><input type="hidden" name="action" value="merge_customer"><label>Customer record to keep<select name="master_customer_id" required><option value="">Choose the complete record</option><?php foreach($customers as $customer):?><option value="<?=$customer['id']?>"><?=e(($customer['company_name']?:$customer['name']).' · #'.$customer['id'].' · '.$customer['linked_records'].' linked')?></option><?php endforeach;?></select></label><label>Duplicate record to merge<select name="source_customer_id" required><option value="">Choose the duplicate</option><?php foreach($customers as $customer):?><option value="<?=$customer['id']?>"><?=e(($customer['company_name']?:$customer['name']).' · #'.$customer['id'].' · '.$customer['linked_records'].' linked')?></option><?php endforeach;?></select></label><label class="check full"><input type="checkbox" name="carry_marketing_consent" value="1"> Carry across promotional consent recorded on either profile</label><label class="check full cleanup-confirm"><input type="checkbox" name="confirm_merge" value="yes" required> I reviewed both records and confirm they belong to the same customer</label><button class="button primary" type="submit" data-confirm="Merge these customers? This moves all linked history into the record being kept.">Merge customers safely</button></form></section>

<section class="cleanup-groups"><div class="panel-head"><div><h2>Suggested duplicates</h2><p>Strong contact matches appear first. Always review before merging.</p></div></div>
<?php foreach($duplicateSets as $set):?><?php $defaultMaster=$set['customers'][0];$defaultSource=$set['customers'][1]??null;?><article class="panel duplicate-group"><header><span><?=e(implode(' · ',array_unique($set['reasons'])))?></span><b><?=count($set['customers'])?> matching records</b></header><div class="duplicate-cards"><?php foreach($set['customers'] as $customer):?><div class="duplicate-card <?=$customer['id']===$defaultMaster['id']?'recommended':''?>"><div><strong><?=e($customer['company_name']?:$customer['name'])?></strong><small>Customer #<?=e((string)$customer['id'])?><?=$customer['id']===$defaultMaster['id']?' · Recommended record to keep':''?></small></div><dl><dt>Contact</dt><dd><?=e($customer['phone']?:$customer['whatsapp']?:'Not supplied')?></dd><dt>Email</dt><dd><?=e($customer['email']?:'Not supplied')?></dd><dt>History</dt><dd><?=$customer['linked_records']?> linked · <?=$customer['document_count']?> documents · <?=$customer['refill_count']?> refills</dd></dl><a class="button secondary small" href="index.php?page=customers&edit=<?=$customer['id']?>">Review profile</a></div><?php endforeach;?></div><?php if($defaultSource):?><form method="post" class="duplicate-quick-merge"><?=csrf_field()?><input type="hidden" name="action" value="merge_customer"><label>Keep<select name="master_customer_id"><?php foreach($set['customers'] as $customer):?><option value="<?=$customer['id']?>" <?=$customer['id']===$defaultMaster['id']?'selected':''?>><?=e(($customer['company_name']?:$customer['name']).' (#'.$customer['id'].')')?></option><?php endforeach;?></select></label><label>Merge duplicate<select name="source_customer_id"><?php foreach($set['customers'] as $customer):?><option value="<?=$customer['id']?>" <?=$customer['id']===$defaultSource['id']?'selected':''?>><?=e(($customer['company_name']?:$customer['name']).' (#'.$customer['id'].')')?></option><?php endforeach;?></select></label><label class="check"><input type="checkbox" name="carry_marketing_consent" value="1"> Preserve either consent</label><label class="check"><input type="checkbox" name="confirm_merge" value="yes" required> Confirm same customer</label><button class="button primary" data-confirm="Merge the selected duplicate into the customer being kept?">Merge</button></form><?php endif;?></article><?php endforeach;?>
<?php if(!$duplicateSets):?><div class="panel cleanup-empty"><b>No strong duplicates found</b><span>You can still use the manual merge tool above when two differently written contacts belong to the same customer.</span></div><?php endif;?></section>

<?php if($unusedDuplicates):?><details class="panel cleanup-delete"><summary>Delete unused duplicate contacts</summary><p>These suggested duplicates have no invoices, orders, CRM work, refills, deliveries, messages or cylinders attached. Deletion is permanent but a protected snapshot is retained in the cleanup log.</p><div><?php foreach($unusedDuplicates as $customer):?><form method="post"><?=csrf_field()?><input type="hidden" name="action" value="delete_unused_customer"><input type="hidden" name="customer_id" value="<?=$customer['id']?>"><input type="hidden" name="confirm_delete" value="yes"><span><b><?=e($customer['company_name']?:$customer['name'])?></b><small>#<?=$customer['id']?> · <?=e($customer['phone']?:$customer['email']?:'No contact details')?></small></span><button class="button danger small" data-confirm="Permanently delete this unused duplicate contact?">Delete unused</button></form><?php endforeach;?></div></details><?php endif;?>
<?php render_footer(); ?>
