<?php
// security_deposit/add_refund.php

error_reporting(-1);
ini_set('display_errors', 1);

include_once('../header.php');
if (!check_login()) {
  header("Location: " . WEB_URL . "logout.php");
  exit;
}

// Helpers (if your project defines these; fall back to $_POST)
if (function_exists('post_input_serilization')) {
  $data = post_input_serilization();
} else {
  $data = $_POST;
}

// Basic validations
$security_deposit_id = isset($data['security_deposit_id']) ? intval($data['security_deposit_id']) : 0;
$refund_amount       = isset($data['refund_amount']) ? floatval($data['refund_amount']) : 0.0;
$new_status          = isset($data['new_status']) ? intval($data['new_status']) : null;

if ($security_deposit_id < 1 || $refund_amount <= 0) {
  $_SESSION["message"] = "Invalid refund request.";
  $_SESSION["message_type"] = "error";
  header("Location: " . WEB_URL . "security_deposit/security_deposit_list.php");
  exit;
}

// Ensure the refund updates table exists (safe no-op if already present)
$link->query("
  CREATE TABLE IF NOT EXISTS `security_deposit_refund_updates` (
    `id` INT NOT NULL AUTO_INCREMENT,
    `security_deposit_id` INT NOT NULL,
    `amount` DECIMAL(18,2) NOT NULL,
    `added_by` INT NULL,
    `added_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    INDEX (`security_deposit_id`)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

// Load the security deposit record
$sd_q = $link->query("
  SELECT `id`, `amt_paid`
  FROM `security_deposit`
  WHERE `id` = {$security_deposit_id}
  LIMIT 1
");

if (!$sd_q || $sd_q->num_rows === 0) {
  $_SESSION["message"] = "Security deposit not found.";
  $_SESSION["message_type"] = "error";
  header("Location: " . WEB_URL . "security_deposit/security_deposit_list.php");
  exit;
}

$sd = $sd_q->fetch_assoc();
$amt_paid = floatval($sd['amt_paid']);

// Sum already refunded
$ref_q = $link->query("
  SELECT COALESCE(SUM(`amount`), 0) AS refunded
  FROM `security_deposit_refund_updates`
  WHERE `security_deposit_id` = {$security_deposit_id}
");
$already_refunded = 0.0;
if ($ref_q && $ref_q->num_rows > 0) {
  $row = $ref_q->fetch_assoc();
  $already_refunded = floatval($row['refunded']);
}

// Check max refundable: cannot exceed (paid - already refunded)
$max_refundable = max(0, $amt_paid - $already_refunded);
if ($refund_amount > $max_refundable + 0.00001) { // tiny epsilon
  $_SESSION["message"] = "Refund exceeds allowable amount. Max refundable is " . number_format($max_refundable, 2) . ".";
  $_SESSION["message_type"] = "error";
  header("Location: " . WEB_URL . "security_deposit/security_deposit_list.php");
  exit;
}

try {
  $link->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);

  // Insert refund record
  $added_by = intval($_SESSION['user_id'] ?? 0);
  $ins_sql = "
    INSERT INTO `security_deposit_refund_updates`
      (`security_deposit_id`, `amount`, `added_by`)
    VALUES
      ({$security_deposit_id}, {$refund_amount}, {$added_by})
  ";
  if (!$link->query($ins_sql)) {
    throw new Exception("Failed to save refund.");
  }

  // If caller requested status change to "Partially Refunded" (3), set it
  if ($new_status === 3) {
    $upd_sql = "
      UPDATE `security_deposit`
      SET `s_status` = 3
      WHERE `id` = {$security_deposit_id}
      LIMIT 1
    ";
    if (!$link->query($upd_sql)) {
      throw new Exception("Failed to update refund status.");
    }
  }

  $link->commit();

  $_SESSION["message"] = "Refund recorded successfully.";
  unset($_SESSION["message_type"]); // success
  header("Location: " . WEB_URL . "security_deposit/security_deposit_list.php");
  exit;

} catch (Exception $e) {
  $link->rollback();
  $_SESSION["message"] = $e->getMessage();
  $_SESSION["message_type"] = "error";
  header("Location: " . WEB_URL . "security_deposit/security_deposit_list.php");
  exit;
}
