1+ <?php
2+ include_once 'connection.php ' ;
3+ if (session_start () === PHP_SESSION_NONE ) {
4+ session_start ();
5+ }
6+ try {
7+ $ user_id = $ _SESSION ['id ' ];
8+ $ cottage_id = $ _POST ['id ' ];
9+ $ start = $ _POST ['start ' ];
10+ $ end = $ _POST ['end ' ];
11+ $ type = $ _POST ['type ' ];
12+
13+ $ current_timestamp = time ();
14+ $ start_timestamp = strtotime ($ start );
15+ $ end_timestamp = strtotime ($ end );
16+
17+ $ sql = "SELECT * FROM transactions WHERE `user_id` = :user_id AND `status` = 'Pending' " ;
18+ $ stmt = $ db ->prepare ($ sql );
19+ $ stmt ->bindParam (':user_id ' , $ user_id );
20+ $ stmt ->execute ();
21+ $ transaction = $ stmt ->fetch (PDO ::FETCH_ASSOC );
22+
23+ $ transaction_id = $ transaction ['id ' ];
24+ $ customer_id = $ transaction ['customer_id ' ];
25+
26+ $ sql = "SELECT * FROM rentals
27+ WHERE `cottage_id` = :cottage_id
28+ AND (:start_datetime BETWEEN `start_datetime` AND `end_datetime`
29+ OR :end_datetime BETWEEN `start_datetime` AND `end_datetime`
30+ OR `start_datetime` BETWEEN :start_datetime AND :end_datetime) " ;
31+ $ stmt = $ db ->prepare ($ sql );
32+ $ stmt ->bindParam (':cottage_id ' , $ cottage_id );
33+ $ stmt ->bindParam (':start_datetime ' , $ start );
34+ $ stmt ->bindParam (':end_datetime ' , $ end );
35+ $ stmt ->execute ();
36+ $ rental = $ stmt ->fetch (PDO ::FETCH_ASSOC );
37+
38+ if ($ rental ) {
39+ header ('Location: ../rent.php?type=error&message=Cottage is already rented on the selected date ' );
40+ exit ;
41+ }
42+
43+ if ($ start_timestamp < $ current_timestamp ) {
44+ header ('Location: ../rent.php?type=error&message=Start date must be greater than current date ' );
45+ exit ;
46+ }
47+ if ($ end_timestamp < $ current_timestamp ) {
48+ header ('Location: ../rent.php?type=error&message=End date must be greater than current date ' );
49+ exit ;
50+ }
51+
52+ if (!$ transaction ) {
53+ header ('Location: ../rent.php?type=error&message=No pending transaction found ' );
54+ }
55+
56+ $ sql = "INSERT INTO rentals (`cottage_id`, `transact_id`, `type`, `start_datetime`, `end_datetime`) VALUES (:cottage_id, :transact_id, :types, :start_datetime, :end_datetime) " ;
57+ $ stmt = $ db ->prepare ($ sql );
58+ $ stmt ->bindParam (':cottage_id ' , $ cottage_id );
59+ $ stmt ->bindParam (':transact_id ' , $ transaction_id );
60+ $ stmt ->bindParam (':types ' , $ type );
61+ $ stmt ->bindParam (':start_datetime ' , $ start );
62+ $ stmt ->bindParam (':end_datetime ' , $ end );
63+ $ stmt ->execute ();
64+
65+ generate_logs ('Add Cottage ' , $ user_id , 'Added new rental ' );
66+ header ('Location: ../rent.php?type=success&message=New transaction was added successfully ' );
67+ } catch (\Throwable $ th ) {
68+ // generate_logs('Add Cottage', 'Error on adding new rental: ' . $th->getMessage());
69+ echo $ th ->getMessage ();
70+ }
71+ ?>
0 commit comments