<?php

// save_financial_contribution_ui.php
// This script handles the POST request to save a financial contribution, 
// ensuring it is linked to the correct historical commitment record.

// ✅ Show all errors during debugging (remove in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);


error_reporting(E_ALL);
ini_set('display_errors', 1);
// Start output buffering to prevent accidental output before header redirection
ob_start(); 

// Include necessary files
include_once 'db_connect.php';    // Must only open $conn (database connection)
// Ensure sms_functions2.php exists and contains logSms(), sendBeemSms(), etc.
include_once 'sms_functions2.php'; 

// --- 1. Authentication and Request Validation ---

$loggedInUserId = 1; // TODO: replace with session user id

// Check if the request method is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    // Redirect to the input form if accessed incorrectly
    header('Location: save_financial_contribution.php');
    exit;
}

// Sanitize and validate inputs
$partner_id         = isset($_POST['partner_id']) ? intval($_POST['partner_id']) : 0;
$agreement_id       = isset($_POST['agreement_id']) ? intval($_POST['agreement_id']) : 0;
$amount             = isset($_POST['amount']) ? floatval($_POST['amount']) : 0.0;
$contribution_date  = $_POST['contribution_date'] ?? '';

// Validate essential inputs
if (!$partner_id || !$agreement_id || $amount <= 0 || !$contribution_date) {
    header('Location: save_financial_contribution.php?error=1&msg=' . urlencode('Missing or invalid required fields (Partner, Agreement, Amount, or Date).'));
    exit;
}

// --- 2. Main Logic Block (Transaction Handling) ---

try {
    // === 1. Get category & prefix (pre-transaction step)
    $catName = 'Partnership Contribution';
    $stmtCat = $conn->prepare("SELECT category_id, receipt_prefix FROM Sadaka_Categories WHERE category_name = ?");
    if (!$stmtCat) throw new Exception("Prepare failed (Sadaka Category fetch): " . $conn->error);
    $stmtCat->bind_param('s', $catName);
    $stmtCat->execute();
    $resCat = $stmtCat->get_result();
    if (!$resCat || $resCat->num_rows === 0) {
        throw new Exception("Category 'Partnership Contribution' not found in Sadaka_Categories table.");
    }
    $catRow = $resCat->fetch_assoc();
    $category_id = (int)$catRow['category_id'];
    $receiptPrefix = $catRow['receipt_prefix'];
    $stmtCat->close();

    // === 2. Find the correct Agreement Commitment History Record ===
    // We look for the active commitment whose date range encompasses the contribution date.
    $stmtCommitment = $conn->prepare("
        SELECT commitment_history_id, commitment_currency 
        FROM Agreement_Commitment_History 
        WHERE agreement_id = ? 
        AND effective_start_date <= ? 
        AND (effective_end_date IS NULL OR effective_end_date >= ?)
        ORDER BY effective_start_date DESC LIMIT 1
    ");
    if (!$stmtCommitment) throw new Exception("Prepare failed (commitment fetch): " . $conn->error);
    // Bind parameters: i (agreement_id), s (contribution_date), s (contribution_date)
    $stmtCommitment->bind_param('iss', $agreement_id, $contribution_date, $contribution_date);
    $stmtCommitment->execute();
    $resCommitment = $stmtCommitment->get_result();
    $commitRow = $resCommitment->fetch_assoc();
    $stmtCommitment->close();

    if (!$commitRow) {
        throw new Exception("No active commitment found for agreement ID {$agreement_id} on {$contribution_date}. Cannot record contribution.");
    }

    $effective_commitment_id = $commitRow['commitment_history_id'];
    $currency = $commitRow['commitment_currency']; // Use the currency defined in the commitment history
    
    // ======================================================================

    // === 3. Start database transaction
    $conn->begin_transaction();

    // Build receipt number based on the last sequence for the day/prefix
    $date_prefix = date('Ymd', strtotime($contribution_date));
    $pattern = $receiptPrefix . $date_prefix . '_%';

    $stmtLast = $conn->prepare("SELECT receipt_number FROM Financial_Contributions WHERE receipt_number LIKE ? ORDER BY receipt_number DESC LIMIT 1");
    if (!$stmtLast) throw new Exception("Prepare failed (last receipt): " . $conn->error);
    $stmtLast->bind_param('s', $pattern);
    $stmtLast->execute();
    $resLast = $stmtLast->get_result();

    $next_seq = 1;
    if ($resLast && $resLast->num_rows > 0) {
        $rowLast = $resLast->fetch_assoc();
        // Extract the last sequence number after the last underscore
        $last_seq = (int) substr($rowLast['receipt_number'], strrpos($rowLast['receipt_number'], '_') + 1);
        $next_seq = $last_seq + 1;
    }
    $stmtLast->close();

    $receipt_number = $receiptPrefix . $date_prefix . '_' . sprintf('%03d', $next_seq);
    $monthOfTheYear = date('F Y', strtotime($contribution_date));
    $jumuiya_collection_id = 1; // Assuming default Jumuiya ID
    $description = "Partnership contribution for agreement {$agreement_id}";

    // === 4. Insert contribution into Financial_Contributions table (UPDATED BIND PARAMETERS)
    $sqlInsert = "INSERT INTO Financial_Contributions 
        (receipt_number, category_id, amount, currency, contribution_date, monthOfTheYear, jumuiya_collection_id, partner_id, agreement_id, effective_commitment_id, description, recorded_by_user_id) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; // 12 parameters

    $stmtIns = $conn->prepare($sqlInsert);
    if (!$stmtIns) throw new Exception("Prepare failed (insert contribution): " . $conn->error);

    $stmtIns->bind_param(
        "sidsssiiisii", // s(receipt), i(category), d(amount), s(currency), s(date), s(month), i(jumuiya), i(partner), i(agreement), i(commitment), s(desc), i(user)
        $receipt_number,
        $category_id,
        $amount,
        $currency, // Fetched from Agreement_Commitment_History
        $contribution_date,
        $monthOfTheYear,
        $jumuiya_collection_id,
        $partner_id,
        $agreement_id,
        $effective_commitment_id, // NEW: Link to the active commitment record
        $description,
        $loggedInUserId
    );

    if (!$stmtIns->execute()) {
        throw new Exception("Insert failed: " . $stmtIns->error);
    }

    $contribution_id = $conn->insert_id;
    $stmtIns->close();

    // Commit contribution before proceeding to SMS
    $conn->commit();

    // --- 5. Post-Commit Actions (SMS & Logging) ---
    
    // === Get partner details for SMS
    $stmtP = $conn->prepare("SELECT partner_name, partner_code, phone_number1 FROM Partners WHERE partner_id = ?");
    if (!$stmtP) throw new Exception("Prepare failed (partner details): " . $conn->error);
    $stmtP->bind_param('i', $partner_id);
    $stmtP->execute();
    $resP = $stmtP->get_result();
    $partner = $resP ? $resP->fetch_assoc() : null;
    $stmtP->close();

    $recipient_phone = '';
    $smsMessage = '';

    if ($partner && !empty($partner['phone_number1'])) {
        $recipient_phone = $partner['phone_number1'];
        $smsMessage = "Asante ndugu {$partner['partner_name']}, kwa mchango wako wa {$currency} " . number_format($amount, 2) . ". Risiti yako: {$receipt_number}.";
    }

    // === Send SMS
    $sendResult = ['status' => 'failed', 'beem_request_id' => null, 'api_response' => '', 'skipped' => true];
    if ($recipient_phone) {
        // Assume sendBeemSms handles the actual API call and returns structured result
        $sendResult = sendBeemSms($conn, $recipient_phone, $smsMessage);
    }

    // === Log SMS result
    $logData = [
        'recipient_phone' => $recipient_phone ?: '',
        'message_content' => $smsMessage ?: '',
        'sent_status' => $sendResult['status'] ?? 'failed',
        'beem_request_id' => $sendResult['beem_request_id'] ?? '',
        'api_response' => $sendResult['api_response'] ?? '',
        'sms_category_id' => 0, // Placeholder
        'related_contribution_id' => $contribution_id,
        'authorized_person_id' => $loggedInUserId,
        'partner_id' => $partner_id,
        'partner_code' => $partner['partner_code'] ?? '',
        'monthYear' => $monthOfTheYear
    ];

    if (!logSms($conn, $logData)) {
        error_log("❌ Failed to save SMS log for contribution {$contribution_id}");
    }

    // === 6. Redirect to success page
    // The success parameter will trigger a dialog/notification on the destination page
    header("Location: save_financial_contribution.php?success=1&receipt=" . urlencode($receipt_number));
    exit;

} catch (Exception $e) {
    // --- 7. Error Handling ---
    if ($conn instanceof mysqli) {
        try {
            // Rollback transaction if any error occurred
            $conn->rollback();
        } catch (Exception $ex) { 
            error_log("Rollback failed: " . $ex->getMessage()); 
        }
    }
    $err = $e->getMessage();
    // Redirect with an error message to display a failure notification
    header("Location: save_financial_contribution.php?error=1&msg=" . urlencode("Contribution failed: " . $err));
    exit;
}

?>