<?php
include "config.php";
include "functions.php";

// Update requests
$sql = "UPDATE requests SET reqStatus = 'rejected', updatedByCron = 1 WHERE reqStatus = 'new' AND TIMESTAMPDIFF(SECOND, reqDate, NOW()) > 60";
$stmt = $pdo->prepare($sql);
$stmt->execute();

if ($stmt->rowCount() > 0) {
    // Fetch reqId values of the updated requests
    $updatedRequestsSql = "SELECT reqId FROM requests WHERE reqStatus = 'rejected' AND updatedByCron = 1 AND TIMESTAMPDIFF(SECOND, reqDate, NOW()) > 60";
    $updatedRequestsStmt = $pdo->prepare($updatedRequestsSql);
    $updatedRequestsStmt->execute();
    $updatedRequestIds = $updatedRequestsStmt->fetchAll(PDO::FETCH_COLUMN);

    // Reset the 'updatedByCron' flag for the next run
    $resetFlagSql = "UPDATE requests SET updatedByCron = 0 WHERE reqStatus = 'rejected' AND updatedByCron = 1 AND TIMESTAMPDIFF(SECOND, reqDate, NOW()) > 60";
    $pdo->exec($resetFlagSql);

    //  Send notifications to users
    foreach ($updatedRequestIds as $updatedRequestId) {
        $userFcmSql = "SELECT userFcm FROM users WHERE userId = (SELECT reqUserId FROM requests WHERE reqId = ?)";
        $userFcmStmt = $pdo->prepare($userFcmSql);
        $userFcmStmt->execute([$updatedRequestId]);
        $fcm = $userFcmStmt->fetchColumn();
        sendGCM("الطلب","تم رفض طلبك ",$fcm,"none","none",true);

        $stmtReqSubSpec=$pdo->prepare("SELECT reqSubSpecId FROM requests WHERE reqId=?");
                $stmtReqSubSpec->execute([$updatedRequestId]);
                $subSpec=$stmtReqSubSpec->fetchColumn();

                if($subSpec==1 || $subSpec==2){
            // decreace 1.5 d from vendor credit if subSpec 1 or 2
            $stmtVendorCredit = $pdo->prepare("UPDATE users SET userCredit = userCredit - 0 WHERE userId = (SELECT reqVenderId FROM requests WHERE reqId = ?)");
            $stmtVendorCredit->execute([$updatedRequestId]);
                }else{   
                    // decreace 2 d from vendor credit
                    $stmtVendorCredit = $pdo->prepare("UPDATE users SET userCredit = userCredit - 2 WHERE userId = (SELECT reqVenderId FROM requests WHERE reqId = ?)");
                    $stmtVendorCredit->execute([$updatedRequestId]);
                }
    
    }
} else {
    // echo "No records were updated.\n";
}