<?php 
session_start();
include '../../connection.php';


if (isset($_POST['loading_transcations_total'])) {


	$query = "SELECT count(*) as total_transctions from tbl_transaction WHERE status = 'Pending'";
	$result = $conn->query($query);
	$row = $result->fetch_assoc();
	$total = $row['total_transctions'];
	echo $total;
}

// ✅ SMS function (your original one)
function sendSms($phoneNumber, $message) {
  $url = 'https://sms.skyio.site/api/sms/send';
  $apiKey = 'AmHGvN3B2Acy9Ql9M96cm89suiEep9Y4EiUVZqQijRKS0RzprzPECSX9ZQeJkLav';
  
  $data = [
    'to' => $phoneNumber,
    'message' => $message
  ];
  
  $curl = curl_init();
  curl_setopt_array($curl, [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => json_encode($data),
    CURLOPT_HTTPHEADER => [
      'Authorization: Bearer ' . $apiKey,
      'Content-Type: application/json',
      'Accept: application/json'
    ],
  ]);
  
  $response = curl_exec($curl);
  $err = curl_error($curl);
  curl_close($curl);
  
  if ($err) {
    return ['success' => false, 'error' => $err];
  } else {
    return json_decode($response, true);
  }
}


// ✅ When updating the transaction
if (isset($_POST['updating_transaction'])) {
    $UniqueID = $_POST['t_id'];
    $status = $_POST['u_status'];

    // Update transaction status
    $query = "UPDATE tbl_transaction SET status = '$status' WHERE UniqueID = '$UniqueID'";
    $result = $conn->query($query);

    if ($result) {
        // Get transaction info again
        $select_txn = "SELECT resident_id FROM tbl_transaction WHERE UniqueID = '$UniqueID'";
        $txn_result = $conn->query($select_txn);
        $txn_row = $txn_result->fetch_assoc();

        $c_id = $txn_row['resident_id'];

        // Get resident info
        $select_resident = "SELECT * FROM tbl_resident WHERE resident_id = '$c_id'";
        $resident_result = $conn->query($select_resident);
        $data = $resident_result->fetch_assoc();

        // Build phone number and message
        $number = '+63' . ltrim($data['contact'], '0');

    // Build full name
$fullname = trim("{$data['first_name']} {$data['middle_name']} {$data['last_name']}");

switch (strtolower($status)) {
    case 'accept':
        $message = "From: Barangay Tual, Good day Ma’am/Sir! {$fullname}, your complaint has been accepted by the Barangay. Please wait for further updates. Thank you.";
        break;

    case 'pending':
        $message = "From: Barangay Tual, Good day Ma’am/Sir! {$fullname}, your complaint is currently pending for review. We will notify you once there’s progress. Thank you.";
        break;

    case 'declined':
        $message = "From: Barangay Tual, Good day Ma’am/Sir! {$fullname}, we regret to inform you that your complaint has been declined. Please visit the Barangay office for clarification.";
        break;

    case 'settled':
        $message = "From: Barangay Tual, Good day Ma’am/Sir! {$fullname}, your complaint has been successfully settled. Thank you for your cooperation.";
        break;

    case 'unsettled':
        $message = "From: Barangay Tual, Good day Ma’am/Sir! {$fullname}, your complaint remains unsettled. Please coordinate with the Barangay office for further action.";
        break;

    default:
        $message = "From: Barangay Tual, Good day Ma’am/Sir! {$fullname}, there is an update regarding your complaint. Please contact the Barangay office for more details.";
        break;
}

        // Send SMS
        $response = sendSms($number, $message);

        // Optional: Check response from SMS API
        if ($response['success'] ?? false) {
            echo "SMS sent successfully!";
        } else {
            echo "Status updated, but SMS failed: " . ($response['error'] ?? 'Unknown error');
        }
    } else {
        echo "Failed to update complaint status.";
    }
}


if (isset($_POST['deleting_transaction'])) {
	$id = $_POST['id'];

	$query = "DELETE FROM tbl_transaction WHERE UniqueID = '$id'";
	$query_result = $conn->query($query);
}

if (isset($_POST['adding_transactions'])) {
	$resident_id = $_POST['resident_id'];
	$incident_address = strtoupper($_POST['incident_address']);
	$complaint_type = $_POST['complaint_type'];
	$description = strtoupper($_POST['description']);
	$date_incident = $_POST['date_incident'];

	$query = "INSERT INTO tbl_transaction (resident_id, incident_address, complaint_type_id, description, incident_date) VALUES ('$resident_id','$incident_address', '$complaint_type', '$description', '$date_incident')";

	$query_result =$conn->query($query);
}

if (isset($_POST['loading_transactions'])) {
	echo 
	'
	<table id="mytable" class="table table-striped table-sm">
  <thead>
    <tr>
      <th scope="col">NO.</th>
      <th scope="col">FULLNAME</th>
      <th scope="col">DESCRIPTION</th>
      <th scope="col">COMPLAINT TYPE</th>
      <th scope="col">STATUS</th>
      <th scope="col">ACTION</th>
    </tr>
  </thead>
  <tbody>
	';

	$query = "SELECT
tbl_transaction.UniqueID,
tbl_transaction.resident_id,
tbl_transaction.description,
tbl_transaction.status,
tbl_transaction.date_created,
tbl_resident.first_name,
tbl_resident.middle_name,
tbl_resident.last_name,
tbl_complaint_types.complain_name

FROM tbl_transaction
LEFT JOIN tbl_resident ON tbl_transaction.resident_id = tbl_resident.resident_id
LEFT JOIN tbl_complaint_types ON tbl_transaction.complaint_type_id = tbl_complaint_types.complaint_type_id";
	$query_result = $conn->query($query);

	$count = 0;

	foreach ($query_result as $key => $row) {
		switch ($row['status']) {
			case 'Accept':
				$badge = "badge badge-info";
				break;
				case 'Pending':
				$badge = "badge badge-primary";
				break;
					case 'Declined':
				$badge = "badge badge-danger";
				break;
					case 'Settled':
				$badge = "badge badge-success";
				break;
					case 'Unsetteled':
				$badge = "badge badge-warning";
				break;
		
		}
		echo 
	'
	 <tr>
      <th scope="row">'.++$count.'</th>
      <td>'.$row['last_name'].', '.$row['first_name'].' '.$row['middle_name'].'</td>
      <td>'.$row['description'].'</td>
       <td>'.$row['complain_name'].'</td>
      <td><span class="'.$badge.'">'.$row['status'].'</span></td>
       <td width="1%" style="white-space: nowrap;">
       <div class="dropdown mb-3">
  <button class="btn btn-secondary btn-sm dropdown-toggle" type="button" data-toggle="dropdown" aria-expanded="false">
    Edit <i class="fa fa-edit"></i>
  </button>
  <div class="dropdown-menu">
    <a class="dropdown-item update-btn" data-status="Accept" data-id="'.$row['UniqueID'].'">
      Accept
      </a>
    <a class="dropdown-item update-btn" data-status="Pending" data-id="'.$row['UniqueID'].'">
      Pending
      </a>
    <a class="dropdown-item update-btn" data-status="Declined" data-id="'.$row['UniqueID'].'">
      Declined
      </a>
    <a class="dropdown-item update-btn" data-status="Settled" data-id="'.$row['UniqueID'].'">
      Settled
      </a>
    <a class="dropdown-item update-btn" data-status="Unsettled" data-id="'.$row['UniqueID'].'">
      Unsettled
      </a>
      <a class="dropdown-item click_page" data-page="transaction_info.php?page='.$row['UniqueID'].'">
      View info
      </a>
      <a class="dropdown-item "  href="pages/form.php?page='.$row['UniqueID'].'" target="__blank">
      Summon Form
      </a>
  </div>
</div>

       </td>
    </tr>
	';
	}


	echo 
	'
	 </tbody>
</table>
	';
}
?>