16000||!is_string($v['state']??null))throw new Exception('Invalid application'); $c=json_decode(file_get_contents('/home/dunerealms/.config/integrations.json'),true); $db=new PDO('mysql:host='.$c['host'].';dbname='.$c['database'].';charset=utf8mb4',$c['username'],$c['password'],[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC]); $db->exec('CREATE TABLE IF NOT EXISTS dune_bank_credit_tickets(application_id CHAR(36) PRIMARY KEY,user_id CHAR(36) NOT NULL,ticket_id INT UNSIGNED NULL UNIQUE,created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP) ENGINE=InnoDB'); $lock=$db->prepare('SELECT GET_LOCK(?,10)');$lock->execute(['bank-credit:'.$v['applicationId']]);if((int)$lock->fetchColumn()!==1)throw new Exception('Busy'); $q=$db->prepare('SELECT * FROM dune_bank_credit_tickets WHERE application_id=?');$q->execute([$v['applicationId']]);$existing=$q->fetch();$recover=null; $subject='Credit application · '.$v['applicationId'];$email=$v['userId'].'@accounts.dunerealms.invalid'; if($existing){ if($existing['user_id']!==$v['userId'])throw new Exception('Applicant binding conflict'); if($existing['ticket_id'])$recover=(int)$existing['ticket_id']; else{ $q=$db->prepare('SELECT DISTINCT t.ticket_id FROM drsupport_ticket t JOIN drsupport_ticket__cdata c ON c.ticket_id=t.ticket_id JOIN drsupport_user_email e ON e.user_id=t.user_id WHERE e.address=? AND c.subject=? AND t.created>=? LIMIT 2');$q->execute([$email,$subject,$existing['created_at']]);$found=$q->fetchAll(PDO::FETCH_COLUMN); if(count($found)!==1)throw new Exception('Interrupted ticket creation requires review; duplicate prevented');$recover=(int)$found[0]; } } $lock->execute(['bank-credit-topic']);if((int)$lock->fetchColumn()!==1)throw new Exception('Intake busy'); $dept=$db->query("SELECT id FROM drsupport_department WHERE name='Sales' LIMIT 1")->fetchColumn();if(!$dept)throw new Exception('Sales intake unavailable'); $topic=$db->query("SELECT topic_id FROM drsupport_help_topic WHERE topic='Bank credit application' LIMIT 1")->fetchColumn(); if(!$topic){ $row=$db->query("SELECT * FROM drsupport_help_topic WHERE topic='General support' LIMIT 1")->fetch();if(!$row)throw new Exception('Intake template unavailable');unset($row['topic_id']);$row['topic']='Bank credit application';$row['ispublic']=0;$row['noautoresp']=1;$row['dept_id']=$dept;$row['team_id']=0;$row['staff_id']=0;$row['created']=$row['updated']=gmdate('Y-m-d H:i:s'); $columns=array_keys($row);$q=$db->prepare('INSERT INTO drsupport_help_topic (`'.implode('`,`',$columns).'`) VALUES('.implode(',',array_fill(0,count($row),'?')).')');$q->execute(array_values($row));$topic=$db->lastInsertId();$q=$db->prepare("INSERT INTO drsupport_help_topic_form(topic_id,form_id,sort,extra) VALUES(?,2,1,'{}')");$q->execute([$topic]); } $db->query("SELECT RELEASE_LOCK('bank-credit-topic')"); $_SERVER['SCRIPT_NAME']='/bank-credit-ticket.php';$_SERVER['REMOTE_ADDR']='127.0.0.1';$_SERVER['REQUEST_METHOD']='POST';$_SERVER['SERVER_NAME']=$_SERVER['HTTP_HOST']='support.dunerealms.com';chdir(__DIR__);require __DIR__.'/main.inc.php'; $name=mb_substr((string)($v['username']??'DuneRealms member'),0,40);$user=User::lookupByEmail($email)?:User::fromVars(['name'=>$name,'email'=>$email]);if(!$user)throw new Exception('Applicant identity unavailable'); if(!$existing){$q=$db->prepare('INSERT INTO dune_bank_credit_tickets(application_id,user_id) VALUES(?,?)');$q->execute([$v['applicationId'],$v['userId']]);} $text='Application: '.$v['applicationId']."\nClient: ".$v['entity']."\nProduct: ".$v['product']."\nPrincipal: ".$v['amount']." DM\nMonthly: ".$v['monthly']." DM\nTerm: ".$v['months']." months\n\nMotivation:\n".$v['motivation']."\n\nReview and decide in Imperial Postbank → Credit Management:\nhttps://cp.dunerealms.com/#bank/loan-administration\n\nThis ticket supports communication. Closing it does not approve a loan, reserve collateral or transfer funds. The bank contract remains authoritative."; $errors=[];$ticket=$recover?Ticket::lookup($recover):Ticket::create(['uid'=>$user->getId(),'name'=>$name,'email'=>$email,'topicId'=>(int)$topic,'deptId'=>(int)$dept,'subject'=>$subject,'message'=>nl2br(htmlspecialchars($text,ENT_QUOTES,'UTF-8')),'source'=>'API','ip'=>'127.0.0.1','autorespond'=>false],$errors,'API',false,false); if(!$ticket)throw new Exception('Ticket creation requires review'); $q=$db->prepare('UPDATE dune_bank_credit_tickets SET ticket_id=? WHERE application_id=?');$q->execute([$ticket->getId(),$v['applicationId']]); $state=$v['state']==='submitted'?'open':'closed'; if($ticket->getStatus()->getState()!==$state){ $q=$db->prepare('SELECT id FROM drsupport_ticket_status WHERE state=? ORDER BY id LIMIT 1');$q->execute([$state]);$status=TicketStatus::lookup((int)$q->fetchColumn());$errors=[]; if(!$status||!$ticket->setStatus($status,$state==='closed'?'Credit review completed or application withdrawn in Imperial Postbank. The bank contract remains authoritative.':'Bank application still awaits a decision in Credit Management.',$errors,false,true))throw new Exception('Ticket status synchronisation failed'); } echo json_encode(['ok'=>true,'ticketId'=>(int)$ticket->getId(),'ticketNumber'=>(string)$ticket->getNumber()]); }catch(Throwable $e){error_log('Bank credit ticket bridge: '.substr($e->getMessage(),0,180));echo '{"error":"Credit support synchronisation pending; duplicate tickets are prevented."}';exit(1);}