<?php
session_start();
include 'layouts/dbconn.php';
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
   echo json_encode(['success' => false, 'error' => 'Not authenticated']);
   exit;
}

try {
   $data = json_decode(file_get_contents('php://input'), true);
   
   if (!$data || !isset($data['corp_id']) || !isset($data['debit_numbers'])) {
       throw new Exception('Invalid input data');
   }
   
   $corp_id = $data['corp_id'];
   $is_new_client = $data['is_new_client'] ?? false;
   $debit_numbers = $data['debit_numbers'];
   $success_count = 0;
   $failed_notes = [];

   foreach ($debit_numbers as $debit_no) {
       // Check if debit note is already allocated
       $sql = "SELECT COUNT(*) as count FROM premium_debit_notes 
               WHERE debit_no = ? AND status != 'UNALLOCATED'";
       $stmt = $conn->prepare($sql);
       $stmt->bind_param('s', $debit_no);
       $stmt->execute();
       $result = $stmt->get_result()->fetch_assoc();

       if ($result['count'] > 0) {
           $failed_notes[] = $debit_no;
           continue;
       }

       // Get debit details
       $sql = "SELECT * FROM premium_debit_notes WHERE debit_no = ? AND corp_id = ?";
       $stmt = $conn->prepare($sql);
       $stmt->bind_param('ss', $debit_no, $corp_id);
       $stmt->execute();
       $debit = $stmt->get_result()->fetch_assoc();

       if (!$debit) {
           $failed_notes[] = $debit_no;
           continue;
       }

       // Calculate commission
       $gross_premium = $debit['amount'];
       $phcf_amount = $gross_premium * 0.0045;
       $new_client_fee = $is_new_client ? 40 : 0;
       $commission_base = $gross_premium - $phcf_amount - $new_client_fee;
       $initial_commission = $commission_base * 0.10;
       $final_commission = $initial_commission * 0.95;

       // Update debit note with commission and status
       $sql = "UPDATE premium_debit_notes SET 
               commission_amount = ?,
               is_new_client = ?,
               commission_calculated = 1,
               calculation_date = NOW(),
               calculated_by = ?,
               status = 'ALLOCATED'
               WHERE debit_no = ? AND status = 'UNALLOCATED'";
               
       $stmt = $conn->prepare($sql);
       $stmt->bind_param('diis', 
           $final_commission,
           $is_new_client,
           $_SESSION['user_id'],
           $debit_no
       );

       if ($stmt->execute() && $stmt->affected_rows > 0) {
           $success_count++;

           // Log activity
           $sql = "INSERT INTO activity_log (
               user_id,
               action,
               table_name,
               record_id,
               new_values,
               action_date
           ) VALUES (?, 'UPDATE', 'premium_debit_notes', ?, ?, NOW())";

           $stmt = $conn->prepare($sql);
           $new_values = json_encode([
               'commission_amount' => $final_commission,
               'is_new_client' => $is_new_client,
               'status' => 'ALLOCATED'
           ]);

           $stmt->bind_param('sss',
               $_SESSION['user_id'],
               $debit_no,
               $new_values
           );
           $stmt->execute();
       } else {
           $failed_notes[] = $debit_no;
       }
   }

   // Prepare response
   if ($success_count === 0) {
       throw new Exception('No debit notes were processed successfully');
   }

   $message = $success_count . ' debit note(s) processed successfully';
   if (!empty($failed_notes)) {
       $message .= '. Failed to process: ' . implode(', ', $failed_notes);
   }

   echo json_encode([
       'success' => true,
       'message' => $message,
       'processed' => $success_count,
       'failed' => count($failed_notes),
       'failed_notes' => $failed_notes
   ]);

} catch (Exception $e) {
   echo json_encode([
       'success' => false,
       'error' => $e->getMessage()
   ]);
}

$conn->close();
?>