<?php

require_once __DIR__.'/database.php';
require_once __DIR__.'/config.php';


function send($chat,$text,$keyboard=null){

$data=[
'chat_id'=>$chat,
'text'=>$text
];

if($keyboard){
$data['reply_markup']=json_encode([
'keyboard'=>$keyboard,
'resize_keyboard'=>true
]);
}

$url="https://api.telegram.org/bot".BOT_TOKEN."/sendMessage";

$ch=curl_init();

curl_setopt_array($ch,[
CURLOPT_URL=>$url,
CURLOPT_POST=>true,
CURLOPT_POSTFIELDS=>$data,
CURLOPT_RETURNTRANSFER=>true
]);

curl_exec($ch);
curl_close($ch);

}



$update=json_decode(file_get_contents("php://input"),true);

if(!$update) exit;


$chat=
$update['message']['chat']['id'];

$text=
trim($update['message']['text'] ?? '');



$stateFile=__DIR__."/state_$chat.txt";
$dataFile=__DIR__."/data_$chat.json";



if($text=="/start"){


send($chat,
"سلام 👋
حسابداری کافی نت سیداصیل فعال شد",
[
[
["text"=>"➕ ثبت بدهکار"]
],
[
["text"=>"💰 بدهی مشتریان"]
]
]);

exit;

}



if($text=="➕ ثبت بدهکار"){


file_put_contents($stateFile,"name");


send($chat,"👤 نام مشتری را وارد کنید:");

exit;

}




$state=@file_get_contents($stateFile);

$data=[];

if(file_exists($dataFile))
$data=json_decode(file_get_contents($dataFile),true);



if($state=="name"){


$data['name']=$text;

file_put_contents($dataFile,json_encode($data));


file_put_contents($stateFile,"mobile");


send($chat,"📱 شماره موبایل مشتری را وارد کنید:");

exit;

}



if($state=="mobile"){


$data['mobile']=$text;


file_put_contents($dataFile,json_encode($data));


file_put_contents($stateFile,"service");


send($chat,"🧾 خدمت انجام شده را وارد کنید:");

exit;

}




if($state=="service"){


$data['service']=$text;


file_put_contents($dataFile,json_encode($data));


file_put_contents($stateFile,"amount");


send($chat,"💰 مبلغ بدهی را وارد کنید:");

exit;

}





if($state=="amount"){


$amount=(int)str_replace(",","",$text);



$stmt=$pdo->prepare(
"INSERT INTO customers(name,mobile)
VALUES(?,?)"
);


$stmt->execute([
$data['name'],
$data['mobile']
]);


$customer=$pdo->lastInsertId();



$stmt=$pdo->prepare(
"INSERT INTO invoices
(customer_id,service,description,total,paid,remain,date_shamsi)
VALUES(?,?,?,?,?,?,?)"
);


$stmt->execute([
$customer,
$data['service'],
"ثبت توسط ربات",
$amount,
0,
$amount,
date("Y/m/d")
]);



unlink($stateFile);
unlink($dataFile);



send($chat,
"✅ بدهی ثبت شد

👤 مشتری:
".$data['name']."

📱 موبایل:
".$data['mobile']."

🧾 خدمت:
".$data['service']."

💰 مبلغ:
".$amount." تومان"

);


exit;

}
