<?php
// check_sms_status.php

// 1. Database Connection
// IMPORTANT: Assumes db_connect.php successfully creates the $conn object.
include 'db_connect.php'; 

// 2. Helper Function for JSON Response
function send_json_response($status, $message, $conn) {
    // Attempt to close the database connection before exiting
    if ($conn && $conn instanceof mysqli && $conn->ping()) {
        $conn->close();
    }
    header('Content-Type: application/json');
    echo json_encode(['status' => $status, 'message' => $message]);
    exit();
}

// 3. Process the POST Request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Safely retrieve inputs
    $partner_id = $_POST['partner_id'] ?? 0;
    $month_year = $_POST['month_year'] ?? ''; // Variable holds the data
    $sms_category_id = $_POST['sms_category_id'] ?? 0;
    $partner_code = $_POST['partner_code'] ?? ''; 

    // Validation
    if (empty($partner_id) || empty($month_year) || empty($sms_category_id)) {
        send_json_response('error', 'Missing required parameters for SMS status check.', $conn);
    }
    
    // Ensure types for security and use in bind_param
    $sms_category_id = (int)$sms_category_id;

    // Corrected SQL: Use the actual column name 'monthYear' from the table
    // and correctly check the 'partner_id' column.
    $sql = "SELECT COUNT(*) AS count 
            FROM SMS_Log 
            WHERE partner_id = ? 
            AND monthYear = ?  -- <<--- FIXED: Changed to monthYear (camelCase)
            AND sms_category_id = ?";
    
    if (!$conn || $conn->connect_error) {
        send_json_response('error', 'Database connection failed: ' . $conn->connect_error, $conn);
    }

    $stmt = $conn->prepare($sql);
    
    if ($stmt) {
        // Corrected bind_param: 's' for partner_id (VARCHAR), 's' for monthYear (VARCHAR), 'i' for sms_category_id (INT)
        $stmt->bind_param("ssi", $partner_id, $month_year, $sms_category_id);
        
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();
        $stmt->close();

        if ($row['count'] > 0) {
            $message = 'Warning: This SMS type has already been sent to Partner ' . htmlspecialchars($partner_code) . ' for ' . htmlspecialchars($month_year) . ' (' . $row['count'] . ' time(s)).';
            send_json_response('exists', $message, $conn);
        } else {
            send_json_response('new', 'OK', $conn);
        }

    } else {
        // Database statement error (e.g., table/column name is wrong or missing)
        send_json_response('error', 'Database statement error. Check SMS_Log table structure. MySQL Error: ' . $conn->error, $conn);
    }

} else {
    // If the file is accessed directly without POST data
    send_json_response('error', 'Invalid request method. Must be POST.', $conn);
}
?>